3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-03-30T20:34:37Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func
239 * @param {number} wait
240 * @param {boolean} immediate
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func
286 * @param {number} wait
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 // Configuration initialization
583 config
= config
|| {};
588 this.data
= config
.data
;
589 this.$element
= config
.$element
||
590 $( document
.createElement( this.getTagName() ) );
591 this.elementGroup
= null;
594 if ( Array
.isArray( config
.classes
) ) {
595 this.$element
.addClass( config
.classes
.join( ' ' ) );
598 this.$element
.attr( 'id', config
.id
);
601 this.$element
.text( config
.text
);
603 if ( config
.content
) {
604 // The `content` property treats plain strings as text; use an
605 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
606 // appropriate $element appended.
607 this.$element
.append( config
.content
.map( function ( v
) {
608 if ( typeof v
=== 'string' ) {
609 // Escape string so it is properly represented in HTML.
610 return document
.createTextNode( v
);
611 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
614 } else if ( v
instanceof OO
.ui
.Element
) {
620 if ( config
.$content
) {
621 // The `$content` property treats plain strings as HTML.
622 this.$element
.append( config
.$content
);
628 OO
.initClass( OO
.ui
.Element
);
630 /* Static Properties */
633 * The name of the HTML tag used by the element.
635 * The static value may be ignored if the #getTagName method is overridden.
641 OO
.ui
.Element
.static.tagName
= 'div';
646 * Reconstitute a JavaScript object corresponding to a widget created
647 * by the PHP implementation.
649 * @param {string|HTMLElement|jQuery} idOrNode
650 * A DOM id (if a string) or node for the widget to infuse.
651 * @return {OO.ui.Element}
652 * The `OO.ui.Element` corresponding to this (infusable) document node.
653 * For `Tag` objects emitted on the HTML side (used occasionally for content)
654 * the value returned is a newly-created Element wrapping around the existing
657 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
658 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
659 // Verify that the type matches up.
660 // FIXME: uncomment after T89721 is fixed (see T90929)
662 if ( !( obj instanceof this['class'] ) ) {
663 throw new Error( 'Infusion type mismatch!' );
670 * Implementation helper for `infuse`; skips the type check and has an
671 * extra property so that only the top-level invocation touches the DOM.
674 * @param {string|HTMLElement|jQuery} idOrNode
675 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
676 * when the top-level widget of this infusion is inserted into DOM,
677 * replacing the original node; or false for top-level invocation.
678 * @return {OO.ui.Element}
680 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
681 // look for a cached result of a previous infusion.
682 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
683 if ( typeof idOrNode
=== 'string' ) {
685 $elem
= $( document
.getElementById( id
) );
687 $elem
= $( idOrNode
);
688 id
= $elem
.attr( 'id' );
690 if ( !$elem
.length
) {
691 throw new Error( 'Widget not found: ' + id
);
693 if ( $elem
[ 0 ].oouiInfused
) {
694 $elem
= $elem
[ 0 ].oouiInfused
;
696 data
= $elem
.data( 'ooui-infused' );
699 if ( data
=== true ) {
700 throw new Error( 'Circular dependency! ' + id
);
703 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
704 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
705 // restore dynamic state after the new element is re-inserted into DOM under infused parent
706 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
707 infusedChildren
= $elem
.data( 'ooui-infused-children' );
708 if ( infusedChildren
&& infusedChildren
.length
) {
709 infusedChildren
.forEach( function ( data
) {
710 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
711 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
717 data
= $elem
.attr( 'data-ooui' );
719 throw new Error( 'No infusion data found: ' + id
);
722 data
= $.parseJSON( data
);
726 if ( !( data
&& data
._
) ) {
727 throw new Error( 'No valid infusion data found: ' + id
);
729 if ( data
._
=== 'Tag' ) {
730 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
731 return new OO
.ui
.Element( { $element
: $elem
} );
733 parts
= data
._
.split( '.' );
734 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
735 if ( cls
=== undefined ) {
736 // The PHP output might be old and not including the "OO.ui" prefix
737 // TODO: Remove this back-compat after next major release
738 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
739 if ( cls
=== undefined ) {
740 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
744 // Verify that we're creating an OO.ui.Element instance
747 while ( parent
!== undefined ) {
748 if ( parent
=== OO
.ui
.Element
) {
753 parent
= parent
.parent
;
756 if ( parent
!== OO
.ui
.Element
) {
757 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
760 if ( domPromise
=== false ) {
762 domPromise
= top
.promise();
764 $elem
.data( 'ooui-infused', true ); // prevent loops
765 data
.id
= id
; // implicit
766 infusedChildren
= [];
767 data
= OO
.copy( data
, null, function deserialize( value
) {
769 if ( OO
.isPlainObject( value
) ) {
771 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
772 infusedChildren
.push( infused
);
773 // Flatten the structure
774 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
775 infused
.$element
.removeData( 'ooui-infused-children' );
778 if ( value
.html
!== undefined ) {
779 return new OO
.ui
.HtmlSnippet( value
.html
);
783 // allow widgets to reuse parts of the DOM
784 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
785 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
786 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
788 // eslint-disable-next-line new-cap
789 obj
= new cls( data
);
790 // now replace old DOM with this new DOM.
792 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
793 // so only mutate the DOM if we need to.
794 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
795 $elem
.replaceWith( obj
.$element
);
796 // This element is now gone from the DOM, but if anyone is holding a reference to it,
797 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
798 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
799 $elem
[ 0 ].oouiInfused
= obj
.$element
;
803 obj
.$element
.data( 'ooui-infused', obj
);
804 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
805 // set the 'data-ooui' attribute so we can identify infused widgets
806 obj
.$element
.attr( 'data-ooui', '' );
807 // restore dynamic state after the new element is inserted into DOM
808 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
813 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
815 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
816 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
817 * constructor, which will be given the enhanced config.
820 * @param {HTMLElement} node
821 * @param {Object} config
824 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
829 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
830 * (and its children) that represent an Element of the same class and the given configuration,
831 * generated by the PHP implementation.
833 * This method is called just before `node` is detached from the DOM. The return value of this
834 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
835 * is inserted into DOM to replace `node`.
838 * @param {HTMLElement} node
839 * @param {Object} config
842 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
847 * Get a jQuery function within a specific document.
850 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
851 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
853 * @return {Function} Bound jQuery function
855 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
856 function wrapper( selector
) {
857 return $( selector
, wrapper
.context
);
860 wrapper
.context
= this.getDocument( context
);
863 wrapper
.$iframe
= $iframe
;
870 * Get the document of an element.
873 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
874 * @return {HTMLDocument|null} Document object
876 OO
.ui
.Element
.static.getDocument = function ( obj
) {
877 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
878 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
879 // Empty jQuery selections might have a context
886 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
891 * Get the window of an element or document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
895 * @return {Window} Window object
897 OO
.ui
.Element
.static.getWindow = function ( obj
) {
898 var doc
= this.getDocument( obj
);
899 return doc
.defaultView
;
903 * Get the direction of an element or document.
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
907 * @return {string} Text direction, either 'ltr' or 'rtl'
909 OO
.ui
.Element
.static.getDir = function ( obj
) {
912 if ( obj
instanceof jQuery
) {
915 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
916 isWin
= obj
.document
!== undefined;
917 if ( isDoc
|| isWin
) {
923 return $( obj
).css( 'direction' );
927 * Get the offset between two frames.
929 * TODO: Make this function not use recursion.
932 * @param {Window} from Window of the child frame
933 * @param {Window} [to=window] Window of the parent frame
934 * @param {Object} [offset] Offset to start with, used internally
935 * @return {Object} Offset object, containing left and top properties
937 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
938 var i
, len
, frames
, frame
, rect
;
944 offset
= { top
: 0, left
: 0 };
946 if ( from.parent
=== from ) {
950 // Get iframe element
951 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
952 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
953 if ( frames
[ i
].contentWindow
=== from ) {
959 // Recursively accumulate offset values
961 rect
= frame
.getBoundingClientRect();
962 offset
.left
+= rect
.left
;
963 offset
.top
+= rect
.top
;
965 this.getFrameOffset( from.parent
, offset
);
972 * Get the offset between two elements.
974 * The two elements may be in a different frame, but in that case the frame $element is in must
975 * be contained in the frame $anchor is in.
978 * @param {jQuery} $element Element whose position to get
979 * @param {jQuery} $anchor Element to get $element's position relative to
980 * @return {Object} Translated position coordinates, containing top and left properties
982 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
983 var iframe
, iframePos
,
984 pos
= $element
.offset(),
985 anchorPos
= $anchor
.offset(),
986 elementDocument
= this.getDocument( $element
),
987 anchorDocument
= this.getDocument( $anchor
);
989 // If $element isn't in the same document as $anchor, traverse up
990 while ( elementDocument
!== anchorDocument
) {
991 iframe
= elementDocument
.defaultView
.frameElement
;
993 throw new Error( '$element frame is not contained in $anchor frame' );
995 iframePos
= $( iframe
).offset();
996 pos
.left
+= iframePos
.left
;
997 pos
.top
+= iframePos
.top
;
998 elementDocument
= iframe
.ownerDocument
;
1000 pos
.left
-= anchorPos
.left
;
1001 pos
.top
-= anchorPos
.top
;
1006 * Get element border sizes.
1009 * @param {HTMLElement} el Element to measure
1010 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1012 OO
.ui
.Element
.static.getBorders = function ( el
) {
1013 var doc
= el
.ownerDocument
,
1014 win
= doc
.defaultView
,
1015 style
= win
.getComputedStyle( el
, null ),
1017 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1018 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1019 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1020 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1031 * Get dimensions of an element or window.
1034 * @param {HTMLElement|Window} el Element to measure
1035 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1037 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1039 doc
= el
.ownerDocument
|| el
.document
,
1040 win
= doc
.defaultView
;
1042 if ( win
=== el
|| el
=== doc
.documentElement
) {
1045 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1047 top
: $win
.scrollTop(),
1048 left
: $win
.scrollLeft()
1050 scrollbar
: { right
: 0, bottom
: 0 },
1054 bottom
: $win
.innerHeight(),
1055 right
: $win
.innerWidth()
1061 borders
: this.getBorders( el
),
1063 top
: $el
.scrollTop(),
1064 left
: $el
.scrollLeft()
1067 right
: $el
.innerWidth() - el
.clientWidth
,
1068 bottom
: $el
.innerHeight() - el
.clientHeight
1070 rect
: el
.getBoundingClientRect()
1076 * Get the number of pixels that an element's content is scrolled to the left.
1078 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1079 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1081 * This function smooths out browser inconsistencies (nicely described in the README at
1082 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1083 * with Firefox's 'scrollLeft', which seems the sanest.
1087 * @param {HTMLElement|Window} el Element to measure
1088 * @return {number} Scroll position from the left.
1089 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1090 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1091 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1092 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1094 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1095 var rtlScrollType
= null;
1098 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1099 definer
= $definer
[ 0 ];
1101 $definer
.appendTo( 'body' );
1102 if ( definer
.scrollLeft
> 0 ) {
1104 rtlScrollType
= 'default';
1106 definer
.scrollLeft
= 1;
1107 if ( definer
.scrollLeft
=== 0 ) {
1108 // Firefox, old Opera
1109 rtlScrollType
= 'negative';
1111 // Internet Explorer, Edge
1112 rtlScrollType
= 'reverse';
1118 return function getScrollLeft( el
) {
1119 var isRoot
= el
.window
=== el
||
1120 el
=== el
.ownerDocument
.body
||
1121 el
=== el
.ownerDocument
.documentElement
,
1122 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1123 // All browsers use the correct scroll type ('negative') on the root, so don't
1124 // do any fixups when looking at the root element
1125 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1127 if ( direction
=== 'rtl' ) {
1128 if ( rtlScrollType
=== null ) {
1131 if ( rtlScrollType
=== 'reverse' ) {
1132 scrollLeft
= -scrollLeft
;
1133 } else if ( rtlScrollType
=== 'default' ) {
1134 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1143 * Get the root scrollable element of given element's document.
1145 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1146 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1147 * lets us use 'body' or 'documentElement' based on what is working.
1149 * https://code.google.com/p/chromium/issues/detail?id=303131
1152 * @param {HTMLElement} el Element to find root scrollable parent for
1153 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1154 * depending on browser
1156 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1157 var scrollTop
, body
;
1159 if ( OO
.ui
.scrollableElement
=== undefined ) {
1160 body
= el
.ownerDocument
.body
;
1161 scrollTop
= body
.scrollTop
;
1164 if ( body
.scrollTop
=== 1 ) {
1165 body
.scrollTop
= scrollTop
;
1166 OO
.ui
.scrollableElement
= 'body';
1168 OO
.ui
.scrollableElement
= 'documentElement';
1172 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1176 * Get closest scrollable container.
1178 * Traverses up until either a scrollable element or the root is reached, in which case the root
1179 * scrollable element will be returned (see #getRootScrollableElement).
1182 * @param {HTMLElement} el Element to find scrollable container for
1183 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1184 * @return {HTMLElement} Closest scrollable container
1186 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1188 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1189 // 'overflow-y' have different values, so we need to check the separate properties.
1190 props
= [ 'overflow-x', 'overflow-y' ],
1191 $parent
= $( el
).parent();
1193 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1194 props
= [ 'overflow-' + dimension
];
1197 // Special case for the document root (which doesn't really have any scrollable container, since
1198 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1199 if ( $( el
).is( 'html, body' ) ) {
1200 return this.getRootScrollableElement( el
);
1203 while ( $parent
.length
) {
1204 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1205 return $parent
[ 0 ];
1209 val
= $parent
.css( props
[ i
] );
1210 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1211 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1212 // unintentionally perform a scroll in such case even if the application doesn't scroll
1213 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1214 // This could cause funny issues...
1215 if ( val
=== 'auto' || val
=== 'scroll' ) {
1216 return $parent
[ 0 ];
1219 $parent
= $parent
.parent();
1221 // The element is unattached... return something mostly sane
1222 return this.getRootScrollableElement( el
);
1226 * Scroll element into view.
1229 * @param {HTMLElement} el Element to scroll into view
1230 * @param {Object} [config] Configuration options
1231 * @param {string} [config.duration='fast'] jQuery animation duration value
1232 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1233 * to scroll in both directions
1234 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1236 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1237 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1238 deferred
= $.Deferred();
1240 // Configuration initialization
1241 config
= config
|| {};
1244 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1245 $container
= $( container
);
1246 elementDimensions
= this.getDimensions( el
);
1247 containerDimensions
= this.getDimensions( container
);
1248 $window
= $( this.getWindow( el
) );
1250 // Compute the element's position relative to the container
1251 if ( $container
.is( 'html, body' ) ) {
1252 // If the scrollable container is the root, this is easy
1254 top
: elementDimensions
.rect
.top
,
1255 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1256 left
: elementDimensions
.rect
.left
,
1257 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1260 // Otherwise, we have to subtract el's coordinates from container's coordinates
1262 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1263 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1264 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1265 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1269 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1270 if ( position
.top
< 0 ) {
1271 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1272 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1273 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1276 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1277 if ( position
.left
< 0 ) {
1278 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1279 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1280 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1283 if ( !$.isEmptyObject( animations
) ) {
1284 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1285 $container
.queue( function ( next
) {
1292 return deferred
.promise();
1296 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1297 * and reserve space for them, because it probably doesn't.
1299 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1300 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1301 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1302 * and then reattach (or show) them back.
1305 * @param {HTMLElement} el Element to reconsider the scrollbars on
1307 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1308 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1309 // Save scroll position
1310 scrollLeft
= el
.scrollLeft
;
1311 scrollTop
= el
.scrollTop
;
1312 // Detach all children
1313 while ( el
.firstChild
) {
1314 nodes
.push( el
.firstChild
);
1315 el
.removeChild( el
.firstChild
);
1318 void el
.offsetHeight
;
1319 // Reattach all children
1320 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1321 el
.appendChild( nodes
[ i
] );
1323 // Restore scroll position (no-op if scrollbars disappeared)
1324 el
.scrollLeft
= scrollLeft
;
1325 el
.scrollTop
= scrollTop
;
1331 * Toggle visibility of an element.
1333 * @param {boolean} [show] Make element visible, omit to toggle visibility
1337 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1338 show
= show
=== undefined ? !this.visible
: !!show
;
1340 if ( show
!== this.isVisible() ) {
1341 this.visible
= show
;
1342 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1343 this.emit( 'toggle', show
);
1350 * Check if element is visible.
1352 * @return {boolean} element is visible
1354 OO
.ui
.Element
.prototype.isVisible = function () {
1355 return this.visible
;
1361 * @return {Mixed} Element data
1363 OO
.ui
.Element
.prototype.getData = function () {
1370 * @param {Mixed} data Element data
1373 OO
.ui
.Element
.prototype.setData = function ( data
) {
1379 * Check if element supports one or more methods.
1381 * @param {string|string[]} methods Method or list of methods to check
1382 * @return {boolean} All methods are supported
1384 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1388 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1389 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1390 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1395 return methods
.length
=== support
;
1399 * Update the theme-provided classes.
1401 * @localdoc This is called in element mixins and widget classes any time state changes.
1402 * Updating is debounced, minimizing overhead of changing multiple attributes and
1403 * guaranteeing that theme updates do not occur within an element's constructor
1405 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1406 OO
.ui
.theme
.queueUpdateElementClasses( this );
1410 * Get the HTML tag name.
1412 * Override this method to base the result on instance information.
1414 * @return {string} HTML tag name
1416 OO
.ui
.Element
.prototype.getTagName = function () {
1417 return this.constructor.static.tagName
;
1421 * Check if the element is attached to the DOM
1423 * @return {boolean} The element is attached to the DOM
1425 OO
.ui
.Element
.prototype.isElementAttached = function () {
1426 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1430 * Get the DOM document.
1432 * @return {HTMLDocument} Document object
1434 OO
.ui
.Element
.prototype.getElementDocument = function () {
1435 // Don't cache this in other ways either because subclasses could can change this.$element
1436 return OO
.ui
.Element
.static.getDocument( this.$element
);
1440 * Get the DOM window.
1442 * @return {Window} Window object
1444 OO
.ui
.Element
.prototype.getElementWindow = function () {
1445 return OO
.ui
.Element
.static.getWindow( this.$element
);
1449 * Get closest scrollable container.
1451 * @return {HTMLElement} Closest scrollable container
1453 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1454 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1458 * Get group element is in.
1460 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1462 OO
.ui
.Element
.prototype.getElementGroup = function () {
1463 return this.elementGroup
;
1467 * Set group element is in.
1469 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1472 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1473 this.elementGroup
= group
;
1478 * Scroll element into view.
1480 * @param {Object} [config] Configuration options
1481 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1483 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1485 !this.isElementAttached() ||
1486 !this.isVisible() ||
1487 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1489 return $.Deferred().resolve();
1491 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1495 * Restore the pre-infusion dynamic state for this widget.
1497 * This method is called after #$element has been inserted into DOM. The parameter is the return
1498 * value of #gatherPreInfuseState.
1501 * @param {Object} state
1503 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1507 * Wraps an HTML snippet for use with configuration values which default
1508 * to strings. This bypasses the default html-escaping done to string
1514 * @param {string} [content] HTML content
1516 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1518 this.content
= content
;
1523 OO
.initClass( OO
.ui
.HtmlSnippet
);
1530 * @return {string} Unchanged HTML snippet.
1532 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1533 return this.content
;
1537 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1538 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1539 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1540 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1541 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1545 * @extends OO.ui.Element
1546 * @mixins OO.EventEmitter
1549 * @param {Object} [config] Configuration options
1551 OO
.ui
.Layout
= function OoUiLayout( config
) {
1552 // Configuration initialization
1553 config
= config
|| {};
1555 // Parent constructor
1556 OO
.ui
.Layout
.parent
.call( this, config
);
1558 // Mixin constructors
1559 OO
.EventEmitter
.call( this );
1562 this.$element
.addClass( 'oo-ui-layout' );
1567 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1568 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1571 * Widgets are compositions of one or more OOjs UI elements that users can both view
1572 * and interact with. All widgets can be configured and modified via a standard API,
1573 * and their state can change dynamically according to a model.
1577 * @extends OO.ui.Element
1578 * @mixins OO.EventEmitter
1581 * @param {Object} [config] Configuration options
1582 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1583 * appearance reflects this state.
1585 OO
.ui
.Widget
= function OoUiWidget( config
) {
1586 // Initialize config
1587 config
= $.extend( { disabled
: false }, config
);
1589 // Parent constructor
1590 OO
.ui
.Widget
.parent
.call( this, config
);
1592 // Mixin constructors
1593 OO
.EventEmitter
.call( this );
1596 this.disabled
= null;
1597 this.wasDisabled
= null;
1600 this.$element
.addClass( 'oo-ui-widget' );
1601 this.setDisabled( !!config
.disabled
);
1606 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1607 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1609 /* Static Properties */
1612 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1613 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1618 * @property {boolean}
1620 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1627 * A 'disable' event is emitted when the disabled state of the widget changes
1628 * (i.e. on disable **and** enable).
1630 * @param {boolean} disabled Widget is disabled
1636 * A 'toggle' event is emitted when the visibility of the widget changes.
1638 * @param {boolean} visible Widget is visible
1644 * Check if the widget is disabled.
1646 * @return {boolean} Widget is disabled
1648 OO
.ui
.Widget
.prototype.isDisabled = function () {
1649 return this.disabled
;
1653 * Set the 'disabled' state of the widget.
1655 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1657 * @param {boolean} disabled Disable widget
1660 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1663 this.disabled
= !!disabled
;
1664 isDisabled
= this.isDisabled();
1665 if ( isDisabled
!== this.wasDisabled
) {
1666 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1667 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1668 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1669 this.emit( 'disable', isDisabled
);
1670 this.updateThemeClasses();
1672 this.wasDisabled
= isDisabled
;
1678 * Update the disabled state, in case of changes in parent widget.
1682 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1683 this.setDisabled( this.disabled
);
1695 OO
.ui
.Theme
= function OoUiTheme() {
1696 this.elementClassesQueue
= [];
1697 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1702 OO
.initClass( OO
.ui
.Theme
);
1707 * Get a list of classes to be applied to a widget.
1709 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1710 * otherwise state transitions will not work properly.
1712 * @param {OO.ui.Element} element Element for which to get classes
1713 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1715 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1716 return { on
: [], off
: [] };
1720 * Update CSS classes provided by the theme.
1722 * For elements with theme logic hooks, this should be called any time there's a state change.
1724 * @param {OO.ui.Element} element Element for which to update classes
1726 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1727 var $elements
= $( [] ),
1728 classes
= this.getElementClasses( element
);
1730 if ( element
.$icon
) {
1731 $elements
= $elements
.add( element
.$icon
);
1733 if ( element
.$indicator
) {
1734 $elements
= $elements
.add( element
.$indicator
);
1738 .removeClass( classes
.off
.join( ' ' ) )
1739 .addClass( classes
.on
.join( ' ' ) );
1745 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1747 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1748 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1751 this.elementClassesQueue
= [];
1755 * Queue #updateElementClasses to be called for this element.
1757 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1758 * to make them synchronous.
1760 * @param {OO.ui.Element} element Element for which to update classes
1762 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1763 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1764 // the most common case (this method is often called repeatedly for the same element).
1765 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1768 this.elementClassesQueue
.push( element
);
1769 this.debouncedUpdateQueuedElementClasses();
1773 * Get the transition duration in milliseconds for dialogs opening/closing
1775 * The dialog should be fully rendered this many milliseconds after the
1776 * ready process has executed.
1778 * @return {number} Transition duration in milliseconds
1780 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1785 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1786 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1787 * order in which users will navigate through the focusable elements via the "tab" key.
1790 * // TabIndexedElement is mixed into the ButtonWidget class
1791 * // to provide a tabIndex property.
1792 * var button1 = new OO.ui.ButtonWidget( {
1796 * var button2 = new OO.ui.ButtonWidget( {
1800 * var button3 = new OO.ui.ButtonWidget( {
1804 * var button4 = new OO.ui.ButtonWidget( {
1808 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1814 * @param {Object} [config] Configuration options
1815 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1816 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1817 * functionality will be applied to it instead.
1818 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1819 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1820 * to remove the element from the tab-navigation flow.
1822 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1823 // Configuration initialization
1824 config
= $.extend( { tabIndex
: 0 }, config
);
1827 this.$tabIndexed
= null;
1828 this.tabIndex
= null;
1831 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1834 this.setTabIndex( config
.tabIndex
);
1835 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1840 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1845 * Set the element that should use the tabindex functionality.
1847 * This method is used to retarget a tabindex mixin so that its functionality applies
1848 * to the specified element. If an element is currently using the functionality, the mixin’s
1849 * effect on that element is removed before the new element is set up.
1851 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1854 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1855 var tabIndex
= this.tabIndex
;
1856 // Remove attributes from old $tabIndexed
1857 this.setTabIndex( null );
1858 // Force update of new $tabIndexed
1859 this.$tabIndexed
= $tabIndexed
;
1860 this.tabIndex
= tabIndex
;
1861 return this.updateTabIndex();
1865 * Set the value of the tabindex.
1867 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1870 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1871 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1873 if ( this.tabIndex
!== tabIndex
) {
1874 this.tabIndex
= tabIndex
;
1875 this.updateTabIndex();
1882 * Update the `tabindex` attribute, in case of changes to tab index or
1888 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1889 if ( this.$tabIndexed
) {
1890 if ( this.tabIndex
!== null ) {
1891 // Do not index over disabled elements
1892 this.$tabIndexed
.attr( {
1893 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1894 // Support: ChromeVox and NVDA
1895 // These do not seem to inherit aria-disabled from parent elements
1896 'aria-disabled': this.isDisabled().toString()
1899 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1906 * Handle disable events.
1909 * @param {boolean} disabled Element is disabled
1911 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1912 this.updateTabIndex();
1916 * Get the value of the tabindex.
1918 * @return {number|null} Tabindex value
1920 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1921 return this.tabIndex
;
1925 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1926 * interface element that can be configured with access keys for accessibility.
1927 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1935 * @param {Object} [config] Configuration options
1936 * @cfg {jQuery} [$button] The button element created by the class.
1937 * If this configuration is omitted, the button element will use a generated `<a>`.
1938 * @cfg {boolean} [framed=true] Render the button with a frame
1940 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1941 // Configuration initialization
1942 config
= config
|| {};
1945 this.$button
= null;
1947 this.active
= config
.active
!== undefined && config
.active
;
1948 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1949 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1950 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1951 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1952 this.onClickHandler
= this.onClick
.bind( this );
1953 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1956 this.$element
.addClass( 'oo-ui-buttonElement' );
1957 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1958 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1963 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1965 /* Static Properties */
1968 * Cancel mouse down events.
1970 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1971 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1972 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1977 * @property {boolean}
1979 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1984 * A 'click' event is emitted when the button element is clicked.
1992 * Set the button element.
1994 * This method is used to retarget a button mixin so that its functionality applies to
1995 * the specified button element instead of the one created by the class. If a button element
1996 * is already set, the method will remove the mixin’s effect on that element.
1998 * @param {jQuery} $button Element to use as button
2000 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2001 if ( this.$button
) {
2003 .removeClass( 'oo-ui-buttonElement-button' )
2004 .removeAttr( 'role accesskey' )
2006 mousedown
: this.onMouseDownHandler
,
2007 keydown
: this.onKeyDownHandler
,
2008 click
: this.onClickHandler
,
2009 keypress
: this.onKeyPressHandler
2013 this.$button
= $button
2014 .addClass( 'oo-ui-buttonElement-button' )
2016 mousedown
: this.onMouseDownHandler
,
2017 keydown
: this.onKeyDownHandler
,
2018 click
: this.onClickHandler
,
2019 keypress
: this.onKeyPressHandler
2022 // Add `role="button"` on `<a>` elements, where it's needed
2023 // `toUppercase()` is added for XHTML documents
2024 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2025 this.$button
.attr( 'role', 'button' );
2030 * Handles mouse down events.
2033 * @param {jQuery.Event} e Mouse down event
2035 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2036 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2039 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2040 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2041 // reliably remove the pressed class
2042 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2043 // Prevent change of focus unless specifically configured otherwise
2044 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2050 * Handles mouse up events.
2053 * @param {MouseEvent} e Mouse up event
2055 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2056 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2059 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2060 // Stop listening for mouseup, since we only needed this once
2061 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2065 * Handles mouse click events.
2068 * @param {jQuery.Event} e Mouse click event
2071 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2072 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2073 if ( this.emit( 'click' ) ) {
2080 * Handles key down events.
2083 * @param {jQuery.Event} e Key down event
2085 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2086 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2089 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2090 // Run the keyup handler no matter where the key is when the button is let go, so we can
2091 // reliably remove the pressed class
2092 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2096 * Handles key up events.
2099 * @param {KeyboardEvent} e Key up event
2101 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2102 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2105 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2106 // Stop listening for keyup, since we only needed this once
2107 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2111 * Handles key press events.
2114 * @param {jQuery.Event} e Key press event
2117 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2118 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2119 if ( this.emit( 'click' ) ) {
2126 * Check if button has a frame.
2128 * @return {boolean} Button is framed
2130 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2135 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2137 * @param {boolean} [framed] Make button framed, omit to toggle
2140 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2141 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2142 if ( framed
!== this.framed
) {
2143 this.framed
= framed
;
2145 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2146 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2147 this.updateThemeClasses();
2154 * Set the button's active state.
2156 * The active state can be set on:
2158 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2159 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2160 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2163 * @param {boolean} value Make button active
2166 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2167 this.active
= !!value
;
2168 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2169 this.updateThemeClasses();
2174 * Check if the button is active
2177 * @return {boolean} The button is active
2179 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2184 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2185 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2186 * items from the group is done through the interface the class provides.
2187 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2189 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2192 * @mixins OO.EmitterList
2196 * @param {Object} [config] Configuration options
2197 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2198 * is omitted, the group element will use a generated `<div>`.
2200 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2201 // Configuration initialization
2202 config
= config
|| {};
2204 // Mixin constructors
2205 OO
.EmitterList
.call( this, config
);
2211 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2216 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2223 * A change event is emitted when the set of selected items changes.
2225 * @param {OO.ui.Element[]} items Items currently in the group
2231 * Set the group element.
2233 * If an element is already set, items will be moved to the new element.
2235 * @param {jQuery} $group Element to use as group
2237 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2240 this.$group
= $group
;
2241 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2242 this.$group
.append( this.items
[ i
].$element
);
2247 * Get an item by its data.
2249 * Only the first item with matching data will be returned. To return all matching items,
2250 * use the #getItemsFromData method.
2252 * @param {Object} data Item data to search for
2253 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2255 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2257 hash
= OO
.getHash( data
);
2259 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2260 item
= this.items
[ i
];
2261 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2270 * Get items by their data.
2272 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2274 * @param {Object} data Item data to search for
2275 * @return {OO.ui.Element[]} Items with equivalent data
2277 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2279 hash
= OO
.getHash( data
),
2282 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2283 item
= this.items
[ i
];
2284 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2293 * Add items to the group.
2295 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2296 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2298 * @param {OO.ui.Element[]} items An array of items to add to the group
2299 * @param {number} [index] Index of the insertion point
2302 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2304 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2306 this.emit( 'change', this.getItems() );
2313 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2314 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2315 this.insertItemElements( items
, newIndex
);
2318 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2326 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2327 item
.setElementGroup( this );
2328 this.insertItemElements( item
, index
);
2331 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2337 * Insert elements into the group
2340 * @param {OO.ui.Element} itemWidget Item to insert
2341 * @param {number} index Insertion index
2343 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2344 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2345 this.$group
.append( itemWidget
.$element
);
2346 } else if ( index
=== 0 ) {
2347 this.$group
.prepend( itemWidget
.$element
);
2349 this.items
[ index
].$element
.before( itemWidget
.$element
);
2354 * Remove the specified items from a group.
2356 * Removed items are detached (not removed) from the DOM so that they may be reused.
2357 * To remove all items from a group, you may wish to use the #clearItems method instead.
2359 * @param {OO.ui.Element[]} items An array of items to remove
2362 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2363 var i
, len
, item
, index
;
2365 // Remove specific items elements
2366 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2368 index
= this.items
.indexOf( item
);
2369 if ( index
!== -1 ) {
2370 item
.setElementGroup( null );
2371 item
.$element
.detach();
2376 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2378 this.emit( 'change', this.getItems() );
2383 * Clear all items from the group.
2385 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2386 * To remove only a subset of items from a group, use the #removeItems method.
2390 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2393 // Remove all item elements
2394 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2395 this.items
[ i
].setElementGroup( null );
2396 this.items
[ i
].$element
.detach();
2400 OO
.EmitterList
.prototype.clearItems
.call( this );
2402 this.emit( 'change', this.getItems() );
2407 * IconElement is often mixed into other classes to generate an icon.
2408 * Icons are graphics, about the size of normal text. They are used to aid the user
2409 * in locating a control or to convey information in a space-efficient way. See the
2410 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2411 * included in the library.
2413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2419 * @param {Object} [config] Configuration options
2420 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2421 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2422 * the icon element be set to an existing icon instead of the one generated by this class, set a
2423 * value using a jQuery selection. For example:
2425 * // Use a <div> tag instead of a <span>
2427 * // Use an existing icon element instead of the one generated by the class
2428 * $icon: this.$element
2429 * // Use an icon element from a child widget
2430 * $icon: this.childwidget.$element
2431 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2432 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2433 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2434 * by the user's language.
2436 * Example of an i18n map:
2438 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2439 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2440 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2441 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2442 * text. The icon title is displayed when users move the mouse over the icon.
2444 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2445 // Configuration initialization
2446 config
= config
|| {};
2451 this.iconTitle
= null;
2454 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2455 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2456 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2461 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2463 /* Static Properties */
2466 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2467 * for i18n purposes and contains a `default` icon name and additional names keyed by
2468 * language code. The `default` name is used when no icon is keyed by the user's language.
2470 * Example of an i18n map:
2472 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2474 * Note: the static property will be overridden if the #icon configuration is used.
2478 * @property {Object|string}
2480 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2483 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2484 * function that returns title text, or `null` for no title.
2486 * The static property will be overridden if the #iconTitle configuration is used.
2490 * @property {string|Function|null}
2492 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2497 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2498 * applies to the specified icon element instead of the one created by the class. If an icon
2499 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2500 * and mixin methods will no longer affect the element.
2502 * @param {jQuery} $icon Element to use as icon
2504 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2507 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2508 .removeAttr( 'title' );
2512 .addClass( 'oo-ui-iconElement-icon' )
2513 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2514 if ( this.iconTitle
!== null ) {
2515 this.$icon
.attr( 'title', this.iconTitle
);
2518 this.updateThemeClasses();
2522 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2523 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2526 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2527 * by language code, or `null` to remove the icon.
2530 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2531 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2532 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2534 if ( this.icon
!== icon
) {
2536 if ( this.icon
!== null ) {
2537 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2539 if ( icon
!== null ) {
2540 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2546 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2547 this.updateThemeClasses();
2553 * Set the icon title. Use `null` to remove the title.
2555 * @param {string|Function|null} iconTitle A text string used as the icon title,
2556 * a function that returns title text, or `null` for no title.
2559 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2560 iconTitle
= typeof iconTitle
=== 'function' ||
2561 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2562 OO
.ui
.resolveMsg( iconTitle
) : null;
2564 if ( this.iconTitle
!== iconTitle
) {
2565 this.iconTitle
= iconTitle
;
2567 if ( this.iconTitle
!== null ) {
2568 this.$icon
.attr( 'title', iconTitle
);
2570 this.$icon
.removeAttr( 'title' );
2579 * Get the symbolic name of the icon.
2581 * @return {string} Icon name
2583 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2588 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2590 * @return {string} Icon title text
2592 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2593 return this.iconTitle
;
2597 * IndicatorElement is often mixed into other classes to generate an indicator.
2598 * Indicators are small graphics that are generally used in two ways:
2600 * - To draw attention to the status of an item. For example, an indicator might be
2601 * used to show that an item in a list has errors that need to be resolved.
2602 * - To clarify the function of a control that acts in an exceptional way (a button
2603 * that opens a menu instead of performing an action directly, for example).
2605 * For a list of indicators included in the library, please see the
2606 * [OOjs UI documentation on MediaWiki] [1].
2608 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2614 * @param {Object} [config] Configuration options
2615 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2616 * configuration is omitted, the indicator element will use a generated `<span>`.
2617 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2618 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2620 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2621 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2622 * or a function that returns title text. The indicator title is displayed when users move
2623 * the mouse over the indicator.
2625 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2626 // Configuration initialization
2627 config
= config
|| {};
2630 this.$indicator
= null;
2631 this.indicator
= null;
2632 this.indicatorTitle
= null;
2635 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2636 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2637 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2642 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2644 /* Static Properties */
2647 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2648 * The static property will be overridden if the #indicator configuration is used.
2652 * @property {string|null}
2654 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2657 * A text string used as the indicator title, a function that returns title text, or `null`
2658 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2662 * @property {string|Function|null}
2664 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2669 * Set the indicator element.
2671 * If an element is already set, it will be cleaned up before setting up the new element.
2673 * @param {jQuery} $indicator Element to use as indicator
2675 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2676 if ( this.$indicator
) {
2678 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2679 .removeAttr( 'title' );
2682 this.$indicator
= $indicator
2683 .addClass( 'oo-ui-indicatorElement-indicator' )
2684 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2685 if ( this.indicatorTitle
!== null ) {
2686 this.$indicator
.attr( 'title', this.indicatorTitle
);
2689 this.updateThemeClasses();
2693 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2695 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2698 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2699 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2701 if ( this.indicator
!== indicator
) {
2702 if ( this.$indicator
) {
2703 if ( this.indicator
!== null ) {
2704 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2706 if ( indicator
!== null ) {
2707 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2710 this.indicator
= indicator
;
2713 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2714 this.updateThemeClasses();
2720 * Set the indicator title.
2722 * The title is displayed when a user moves the mouse over the indicator.
2724 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2725 * `null` for no indicator title
2728 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2729 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2730 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2731 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2733 if ( this.indicatorTitle
!== indicatorTitle
) {
2734 this.indicatorTitle
= indicatorTitle
;
2735 if ( this.$indicator
) {
2736 if ( this.indicatorTitle
!== null ) {
2737 this.$indicator
.attr( 'title', indicatorTitle
);
2739 this.$indicator
.removeAttr( 'title' );
2748 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2750 * @return {string} Symbolic name of indicator
2752 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2753 return this.indicator
;
2757 * Get the indicator title.
2759 * The title is displayed when a user moves the mouse over the indicator.
2761 * @return {string} Indicator title text
2763 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2764 return this.indicatorTitle
;
2768 * LabelElement is often mixed into other classes to generate a label, which
2769 * helps identify the function of an interface element.
2770 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2778 * @param {Object} [config] Configuration options
2779 * @cfg {jQuery} [$label] The label element created by the class. If this
2780 * configuration is omitted, the label element will use a generated `<span>`.
2781 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2782 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2783 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2784 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2786 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2787 // Configuration initialization
2788 config
= config
|| {};
2795 this.setLabel( config
.label
|| this.constructor.static.label
);
2796 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2801 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2806 * @event labelChange
2807 * @param {string} value
2810 /* Static Properties */
2813 * The label text. The label can be specified as a plaintext string, a function that will
2814 * produce a string in the future, or `null` for no label. The static value will
2815 * be overridden if a label is specified with the #label config option.
2819 * @property {string|Function|null}
2821 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2823 /* Static methods */
2826 * Highlight the first occurrence of the query in the given text
2828 * @param {string} text Text
2829 * @param {string} query Query to find
2830 * @return {jQuery} Text with the first match of the query
2831 * sub-string wrapped in highlighted span
2833 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2834 var $result
= $( '<span>' ),
2835 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2837 if ( !query
.length
|| offset
=== -1 ) {
2838 return $result
.text( text
);
2841 document
.createTextNode( text
.slice( 0, offset
) ),
2843 .addClass( 'oo-ui-labelElement-label-highlight' )
2844 .text( text
.slice( offset
, offset
+ query
.length
) ),
2845 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2847 return $result
.contents();
2853 * Set the label element.
2855 * If an element is already set, it will be cleaned up before setting up the new element.
2857 * @param {jQuery} $label Element to use as label
2859 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2860 if ( this.$label
) {
2861 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2864 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2865 this.setLabelContent( this.label
);
2871 * An empty string will result in the label being hidden. A string containing only whitespace will
2872 * be converted to a single ` `.
2874 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2875 * text; or null for no label
2878 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2879 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2880 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2882 if ( this.label
!== label
) {
2883 if ( this.$label
) {
2884 this.setLabelContent( label
);
2887 this.emit( 'labelChange' );
2890 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2896 * Set the label as plain text with a highlighted query
2898 * @param {string} text Text label to set
2899 * @param {string} query Substring of text to highlight
2902 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2903 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2909 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2910 * text; or null for no label
2912 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2917 * Set the content of the label.
2919 * Do not call this method until after the label element has been set by #setLabelElement.
2922 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2923 * text; or null for no label
2925 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2926 if ( typeof label
=== 'string' ) {
2927 if ( label
.match( /^\s*$/ ) ) {
2928 // Convert whitespace only string to a single non-breaking space
2929 this.$label
.html( ' ' );
2931 this.$label
.text( label
);
2933 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2934 this.$label
.html( label
.toString() );
2935 } else if ( label
instanceof jQuery
) {
2936 this.$label
.empty().append( label
);
2938 this.$label
.empty();
2943 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2944 * additional functionality to an element created by another class. The class provides
2945 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2946 * which are used to customize the look and feel of a widget to better describe its
2947 * importance and functionality.
2949 * The library currently contains the following styling flags for general use:
2951 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2952 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2953 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2955 * The flags affect the appearance of the buttons:
2958 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2959 * var button1 = new OO.ui.ButtonWidget( {
2960 * label: 'Constructive',
2961 * flags: 'constructive'
2963 * var button2 = new OO.ui.ButtonWidget( {
2964 * label: 'Destructive',
2965 * flags: 'destructive'
2967 * var button3 = new OO.ui.ButtonWidget( {
2968 * label: 'Progressive',
2969 * flags: 'progressive'
2971 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2973 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2974 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2976 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2982 * @param {Object} [config] Configuration options
2983 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2984 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2985 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2986 * @cfg {jQuery} [$flagged] The flagged element. By default,
2987 * the flagged functionality is applied to the element created by the class ($element).
2988 * If a different element is specified, the flagged functionality will be applied to it instead.
2990 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2991 // Configuration initialization
2992 config
= config
|| {};
2996 this.$flagged
= null;
2999 this.setFlags( config
.flags
);
3000 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3007 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3008 * parameter contains the name of each modified flag and indicates whether it was
3011 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3012 * that the flag was added, `false` that the flag was removed.
3018 * Set the flagged element.
3020 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3021 * If an element is already set, the method will remove the mixin’s effect on that element.
3023 * @param {jQuery} $flagged Element that should be flagged
3025 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3026 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3027 return 'oo-ui-flaggedElement-' + flag
;
3030 if ( this.$flagged
) {
3031 this.$flagged
.removeClass( classNames
);
3034 this.$flagged
= $flagged
.addClass( classNames
);
3038 * Check if the specified flag is set.
3040 * @param {string} flag Name of flag
3041 * @return {boolean} The flag is set
3043 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3044 // This may be called before the constructor, thus before this.flags is set
3045 return this.flags
&& ( flag
in this.flags
);
3049 * Get the names of all flags set.
3051 * @return {string[]} Flag names
3053 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3054 // This may be called before the constructor, thus before this.flags is set
3055 return Object
.keys( this.flags
|| {} );
3064 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3065 var flag
, className
,
3068 classPrefix
= 'oo-ui-flaggedElement-';
3070 for ( flag
in this.flags
) {
3071 className
= classPrefix
+ flag
;
3072 changes
[ flag
] = false;
3073 delete this.flags
[ flag
];
3074 remove
.push( className
);
3077 if ( this.$flagged
) {
3078 this.$flagged
.removeClass( remove
.join( ' ' ) );
3081 this.updateThemeClasses();
3082 this.emit( 'flag', changes
);
3088 * Add one or more flags.
3090 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3091 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3092 * be added (`true`) or removed (`false`).
3096 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3097 var i
, len
, flag
, className
,
3101 classPrefix
= 'oo-ui-flaggedElement-';
3103 if ( typeof flags
=== 'string' ) {
3104 className
= classPrefix
+ flags
;
3106 if ( !this.flags
[ flags
] ) {
3107 this.flags
[ flags
] = true;
3108 add
.push( className
);
3110 } else if ( Array
.isArray( flags
) ) {
3111 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3113 className
= classPrefix
+ flag
;
3115 if ( !this.flags
[ flag
] ) {
3116 changes
[ flag
] = true;
3117 this.flags
[ flag
] = true;
3118 add
.push( className
);
3121 } else if ( OO
.isPlainObject( flags
) ) {
3122 for ( flag
in flags
) {
3123 className
= classPrefix
+ flag
;
3124 if ( flags
[ flag
] ) {
3126 if ( !this.flags
[ flag
] ) {
3127 changes
[ flag
] = true;
3128 this.flags
[ flag
] = true;
3129 add
.push( className
);
3133 if ( this.flags
[ flag
] ) {
3134 changes
[ flag
] = false;
3135 delete this.flags
[ flag
];
3136 remove
.push( className
);
3142 if ( this.$flagged
) {
3144 .addClass( add
.join( ' ' ) )
3145 .removeClass( remove
.join( ' ' ) );
3148 this.updateThemeClasses();
3149 this.emit( 'flag', changes
);
3155 * TitledElement is mixed into other classes to provide a `title` attribute.
3156 * Titles are rendered by the browser and are made visible when the user moves
3157 * the mouse over the element. Titles are not visible on touch devices.
3160 * // TitledElement provides a 'title' attribute to the
3161 * // ButtonWidget class
3162 * var button = new OO.ui.ButtonWidget( {
3163 * label: 'Button with Title',
3164 * title: 'I am a button'
3166 * $( 'body' ).append( button.$element );
3172 * @param {Object} [config] Configuration options
3173 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3174 * If this config is omitted, the title functionality is applied to $element, the
3175 * element created by the class.
3176 * @cfg {string|Function} [title] The title text or a function that returns text. If
3177 * this config is omitted, the value of the {@link #static-title static title} property is used.
3179 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3180 // Configuration initialization
3181 config
= config
|| {};
3184 this.$titled
= null;
3188 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3189 this.setTitledElement( config
.$titled
|| this.$element
);
3194 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3196 /* Static Properties */
3199 * The title text, a function that returns text, or `null` for no title. The value of the static property
3200 * is overridden if the #title config option is used.
3204 * @property {string|Function|null}
3206 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3211 * Set the titled element.
3213 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3214 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3216 * @param {jQuery} $titled Element that should use the 'titled' functionality
3218 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3219 if ( this.$titled
) {
3220 this.$titled
.removeAttr( 'title' );
3223 this.$titled
= $titled
;
3225 this.$titled
.attr( 'title', this.title
);
3232 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3235 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3236 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3237 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3239 if ( this.title
!== title
) {
3240 if ( this.$titled
) {
3241 if ( title
!== null ) {
3242 this.$titled
.attr( 'title', title
);
3244 this.$titled
.removeAttr( 'title' );
3256 * @return {string} Title string
3258 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3263 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3264 * Accesskeys allow an user to go to a specific element by using
3265 * a shortcut combination of a browser specific keys + the key
3269 * // AccessKeyedElement provides an 'accesskey' attribute to the
3270 * // ButtonWidget class
3271 * var button = new OO.ui.ButtonWidget( {
3272 * label: 'Button with Accesskey',
3275 * $( 'body' ).append( button.$element );
3281 * @param {Object} [config] Configuration options
3282 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3283 * If this config is omitted, the accesskey functionality is applied to $element, the
3284 * element created by the class.
3285 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3286 * this config is omitted, no accesskey will be added.
3288 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3289 // Configuration initialization
3290 config
= config
|| {};
3293 this.$accessKeyed
= null;
3294 this.accessKey
= null;
3297 this.setAccessKey( config
.accessKey
|| null );
3298 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3303 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3305 /* Static Properties */
3308 * The access key, a function that returns a key, or `null` for no accesskey.
3312 * @property {string|Function|null}
3314 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3319 * Set the accesskeyed element.
3321 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3322 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3324 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3326 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3327 if ( this.$accessKeyed
) {
3328 this.$accessKeyed
.removeAttr( 'accesskey' );
3331 this.$accessKeyed
= $accessKeyed
;
3332 if ( this.accessKey
) {
3333 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3340 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3343 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3344 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3346 if ( this.accessKey
!== accessKey
) {
3347 if ( this.$accessKeyed
) {
3348 if ( accessKey
!== null ) {
3349 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3351 this.$accessKeyed
.removeAttr( 'accesskey' );
3354 this.accessKey
= accessKey
;
3363 * @return {string} accessKey string
3365 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3366 return this.accessKey
;
3370 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3371 * feels, and functionality can be customized via the class’s configuration options
3372 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3375 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3378 * // A button widget
3379 * var button = new OO.ui.ButtonWidget( {
3380 * label: 'Button with Icon',
3382 * iconTitle: 'Remove'
3384 * $( 'body' ).append( button.$element );
3386 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3389 * @extends OO.ui.Widget
3390 * @mixins OO.ui.mixin.ButtonElement
3391 * @mixins OO.ui.mixin.IconElement
3392 * @mixins OO.ui.mixin.IndicatorElement
3393 * @mixins OO.ui.mixin.LabelElement
3394 * @mixins OO.ui.mixin.TitledElement
3395 * @mixins OO.ui.mixin.FlaggedElement
3396 * @mixins OO.ui.mixin.TabIndexedElement
3397 * @mixins OO.ui.mixin.AccessKeyedElement
3400 * @param {Object} [config] Configuration options
3401 * @cfg {boolean} [active=false] Whether button should be shown as active
3402 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3403 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3404 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3406 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3407 // Configuration initialization
3408 config
= config
|| {};
3410 // Parent constructor
3411 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3413 // Mixin constructors
3414 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3415 OO
.ui
.mixin
.IconElement
.call( this, config
);
3416 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3417 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3418 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3419 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3420 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3421 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3426 this.noFollow
= false;
3429 this.connect( this, { disable
: 'onDisable' } );
3432 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3434 .addClass( 'oo-ui-buttonWidget' )
3435 .append( this.$button
);
3436 this.setActive( config
.active
);
3437 this.setHref( config
.href
);
3438 this.setTarget( config
.target
);
3439 this.setNoFollow( config
.noFollow
);
3444 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3445 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3446 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3447 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3448 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3449 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3450 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3451 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3452 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3454 /* Static Properties */
3460 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3466 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3471 * Get hyperlink location.
3473 * @return {string} Hyperlink location
3475 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3480 * Get hyperlink target.
3482 * @return {string} Hyperlink target
3484 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3489 * Get search engine traversal hint.
3491 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3493 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3494 return this.noFollow
;
3498 * Set hyperlink location.
3500 * @param {string|null} href Hyperlink location, null to remove
3502 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3503 href
= typeof href
=== 'string' ? href
: null;
3504 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3508 if ( href
!== this.href
) {
3517 * Update the `href` attribute, in case of changes to href or
3523 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3524 if ( this.href
!== null && !this.isDisabled() ) {
3525 this.$button
.attr( 'href', this.href
);
3527 this.$button
.removeAttr( 'href' );
3534 * Handle disable events.
3537 * @param {boolean} disabled Element is disabled
3539 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3544 * Set hyperlink target.
3546 * @param {string|null} target Hyperlink target, null to remove
3548 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3549 target
= typeof target
=== 'string' ? target
: null;
3551 if ( target
!== this.target
) {
3552 this.target
= target
;
3553 if ( target
!== null ) {
3554 this.$button
.attr( 'target', target
);
3556 this.$button
.removeAttr( 'target' );
3564 * Set search engine traversal hint.
3566 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3568 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3569 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3571 if ( noFollow
!== this.noFollow
) {
3572 this.noFollow
= noFollow
;
3574 this.$button
.attr( 'rel', 'nofollow' );
3576 this.$button
.removeAttr( 'rel' );
3583 // Override method visibility hints from ButtonElement
3592 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3593 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3594 * removed, and cleared from the group.
3597 * // Example: A ButtonGroupWidget with two buttons
3598 * var button1 = new OO.ui.PopupButtonWidget( {
3599 * label: 'Select a category',
3602 * $content: $( '<p>List of categories...</p>' ),
3607 * var button2 = new OO.ui.ButtonWidget( {
3610 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3611 * items: [button1, button2]
3613 * $( 'body' ).append( buttonGroup.$element );
3616 * @extends OO.ui.Widget
3617 * @mixins OO.ui.mixin.GroupElement
3620 * @param {Object} [config] Configuration options
3621 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3623 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3624 // Configuration initialization
3625 config
= config
|| {};
3627 // Parent constructor
3628 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3630 // Mixin constructors
3631 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3634 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3635 if ( Array
.isArray( config
.items
) ) {
3636 this.addItems( config
.items
);
3642 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3643 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3645 /* Static Properties */
3651 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3654 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3655 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3656 * for a list of icons included in the library.
3659 * // An icon widget with a label
3660 * var myIcon = new OO.ui.IconWidget( {
3664 * // Create a label.
3665 * var iconLabel = new OO.ui.LabelWidget( {
3668 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3670 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3673 * @extends OO.ui.Widget
3674 * @mixins OO.ui.mixin.IconElement
3675 * @mixins OO.ui.mixin.TitledElement
3676 * @mixins OO.ui.mixin.FlaggedElement
3679 * @param {Object} [config] Configuration options
3681 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3682 // Configuration initialization
3683 config
= config
|| {};
3685 // Parent constructor
3686 OO
.ui
.IconWidget
.parent
.call( this, config
);
3688 // Mixin constructors
3689 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3690 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3691 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3694 this.$element
.addClass( 'oo-ui-iconWidget' );
3699 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3700 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3701 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3702 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3704 /* Static Properties */
3710 OO
.ui
.IconWidget
.static.tagName
= 'span';
3713 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3714 * attention to the status of an item or to clarify the function of a control. For a list of
3715 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3718 * // Example of an indicator widget
3719 * var indicator1 = new OO.ui.IndicatorWidget( {
3720 * indicator: 'alert'
3723 * // Create a fieldset layout to add a label
3724 * var fieldset = new OO.ui.FieldsetLayout();
3725 * fieldset.addItems( [
3726 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3728 * $( 'body' ).append( fieldset.$element );
3730 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3733 * @extends OO.ui.Widget
3734 * @mixins OO.ui.mixin.IndicatorElement
3735 * @mixins OO.ui.mixin.TitledElement
3738 * @param {Object} [config] Configuration options
3740 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3741 // Configuration initialization
3742 config
= config
|| {};
3744 // Parent constructor
3745 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3747 // Mixin constructors
3748 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3749 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3752 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3757 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3758 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3759 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3761 /* Static Properties */
3767 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3770 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3771 * be configured with a `label` option that is set to a string, a label node, or a function:
3773 * - String: a plaintext string
3774 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3775 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3776 * - Function: a function that will produce a string in the future. Functions are used
3777 * in cases where the value of the label is not currently defined.
3779 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3780 * will come into focus when the label is clicked.
3783 * // Examples of LabelWidgets
3784 * var label1 = new OO.ui.LabelWidget( {
3785 * label: 'plaintext label'
3787 * var label2 = new OO.ui.LabelWidget( {
3788 * label: $( '<a href="default.html">jQuery label</a>' )
3790 * // Create a fieldset layout with fields for each example
3791 * var fieldset = new OO.ui.FieldsetLayout();
3792 * fieldset.addItems( [
3793 * new OO.ui.FieldLayout( label1 ),
3794 * new OO.ui.FieldLayout( label2 )
3796 * $( 'body' ).append( fieldset.$element );
3799 * @extends OO.ui.Widget
3800 * @mixins OO.ui.mixin.LabelElement
3801 * @mixins OO.ui.mixin.TitledElement
3804 * @param {Object} [config] Configuration options
3805 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3806 * Clicking the label will focus the specified input field.
3808 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3809 // Configuration initialization
3810 config
= config
|| {};
3812 // Parent constructor
3813 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3815 // Mixin constructors
3816 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3817 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3820 this.input
= config
.input
;
3823 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3824 if ( this.input
.getInputId() ) {
3825 this.$element
.attr( 'for', this.input
.getInputId() );
3827 this.$label
.on( 'click', function () {
3828 this.fieldWidget
.focus();
3833 this.$element
.addClass( 'oo-ui-labelWidget' );
3838 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3839 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3840 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3842 /* Static Properties */
3848 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3851 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3852 * and that they should wait before proceeding. The pending state is visually represented with a pending
3853 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3854 * field of a {@link OO.ui.TextInputWidget text input widget}.
3856 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3857 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3858 * in process dialogs.
3861 * function MessageDialog( config ) {
3862 * MessageDialog.parent.call( this, config );
3864 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3866 * MessageDialog.static.name = 'myMessageDialog';
3867 * MessageDialog.static.actions = [
3868 * { action: 'save', label: 'Done', flags: 'primary' },
3869 * { label: 'Cancel', flags: 'safe' }
3872 * MessageDialog.prototype.initialize = function () {
3873 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3874 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3875 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
3876 * this.$body.append( this.content.$element );
3878 * MessageDialog.prototype.getBodyHeight = function () {
3881 * MessageDialog.prototype.getActionProcess = function ( action ) {
3882 * var dialog = this;
3883 * if ( action === 'save' ) {
3884 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3885 * return new OO.ui.Process()
3887 * .next( function () {
3888 * dialog.getActions().get({actions: 'save'})[0].popPending();
3891 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3894 * var windowManager = new OO.ui.WindowManager();
3895 * $( 'body' ).append( windowManager.$element );
3897 * var dialog = new MessageDialog();
3898 * windowManager.addWindows( [ dialog ] );
3899 * windowManager.openWindow( dialog );
3905 * @param {Object} [config] Configuration options
3906 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3908 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3909 // Configuration initialization
3910 config
= config
|| {};
3914 this.$pending
= null;
3917 this.setPendingElement( config
.$pending
|| this.$element
);
3922 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3927 * Set the pending element (and clean up any existing one).
3929 * @param {jQuery} $pending The element to set to pending.
3931 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3932 if ( this.$pending
) {
3933 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3936 this.$pending
= $pending
;
3937 if ( this.pending
> 0 ) {
3938 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3943 * Check if an element is pending.
3945 * @return {boolean} Element is pending
3947 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3948 return !!this.pending
;
3952 * Increase the pending counter. The pending state will remain active until the counter is zero
3953 * (i.e., the number of calls to #pushPending and #popPending is the same).
3957 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3958 if ( this.pending
=== 0 ) {
3959 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3960 this.updateThemeClasses();
3968 * Decrease the pending counter. The pending state will remain active until the counter is zero
3969 * (i.e., the number of calls to #pushPending and #popPending is the same).
3973 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3974 if ( this.pending
=== 1 ) {
3975 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3976 this.updateThemeClasses();
3978 this.pending
= Math
.max( 0, this.pending
- 1 );
3984 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
3985 * in the document (for example, in an OO.ui.Window's $overlay).
3987 * The elements's position is automatically calculated and maintained when window is resized or the
3988 * page is scrolled. If you reposition the container manually, you have to call #position to make
3989 * sure the element is still placed correctly.
3991 * As positioning is only possible when both the element and the container are attached to the DOM
3992 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
3993 * the #toggle method to display a floating popup, for example.
3999 * @param {Object} [config] Configuration options
4000 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4001 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4002 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4003 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4004 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4005 * 'top': Align the top edge with $floatableContainer's top edge
4006 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4007 * 'center': Vertically align the center with $floatableContainer's center
4008 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4009 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4010 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4011 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4012 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4013 * 'center': Horizontally align the center with $floatableContainer's center
4014 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4017 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4018 // Configuration initialization
4019 config
= config
|| {};
4022 this.$floatable
= null;
4023 this.$floatableContainer
= null;
4024 this.$floatableWindow
= null;
4025 this.$floatableClosestScrollable
= null;
4026 this.onFloatableScrollHandler
= this.position
.bind( this );
4027 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4030 this.setFloatableContainer( config
.$floatableContainer
);
4031 this.setFloatableElement( config
.$floatable
|| this.$element
);
4032 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4033 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4034 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4040 * Set floatable element.
4042 * If an element is already set, it will be cleaned up before setting up the new element.
4044 * @param {jQuery} $floatable Element to make floatable
4046 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4047 if ( this.$floatable
) {
4048 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4049 this.$floatable
.css( { left
: '', top
: '' } );
4052 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4057 * Set floatable container.
4059 * The element will be positioned relative to the specified container.
4061 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4063 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4064 this.$floatableContainer
= $floatableContainer
;
4065 if ( this.$floatable
) {
4071 * Change how the element is positioned vertically.
4073 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4075 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4076 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4077 throw new Error( 'Invalid value for vertical position: ' + position
);
4079 if ( this.verticalPosition
!== position
) {
4080 this.verticalPosition
= position
;
4081 if ( this.$floatable
) {
4088 * Change how the element is positioned horizontally.
4090 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4092 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4093 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4094 throw new Error( 'Invalid value for horizontal position: ' + position
);
4096 if ( this.horizontalPosition
!== position
) {
4097 this.horizontalPosition
= position
;
4098 if ( this.$floatable
) {
4105 * Toggle positioning.
4107 * Do not turn positioning on until after the element is attached to the DOM and visible.
4109 * @param {boolean} [positioning] Enable positioning, omit to toggle
4112 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4113 var closestScrollableOfContainer
;
4115 if ( !this.$floatable
|| !this.$floatableContainer
) {
4119 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4121 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4122 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4123 this.warnedUnattached
= true;
4126 if ( this.positioning
!== positioning
) {
4127 this.positioning
= positioning
;
4129 this.needsCustomPosition
=
4130 this.verticalPostion
!== 'below' ||
4131 this.horizontalPosition
!== 'start' ||
4132 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4134 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4135 // If the scrollable is the root, we have to listen to scroll events
4136 // on the window because of browser inconsistencies.
4137 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4138 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4141 if ( positioning
) {
4142 this.$floatableWindow
= $( this.getElementWindow() );
4143 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4145 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4146 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4148 // Initial position after visible
4151 if ( this.$floatableWindow
) {
4152 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4153 this.$floatableWindow
= null;
4156 if ( this.$floatableClosestScrollable
) {
4157 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4158 this.$floatableClosestScrollable
= null;
4161 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4169 * Check whether the bottom edge of the given element is within the viewport of the given container.
4172 * @param {jQuery} $element
4173 * @param {jQuery} $container
4176 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4177 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4178 startEdgeInBounds
, endEdgeInBounds
,
4179 direction
= $element
.css( 'direction' );
4181 elemRect
= $element
[ 0 ].getBoundingClientRect();
4182 if ( $container
[ 0 ] === window
) {
4186 right
: document
.documentElement
.clientWidth
,
4187 bottom
: document
.documentElement
.clientHeight
4190 contRect
= $container
[ 0 ].getBoundingClientRect();
4193 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4194 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4195 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4196 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4197 if ( direction
=== 'rtl' ) {
4198 startEdgeInBounds
= rightEdgeInBounds
;
4199 endEdgeInBounds
= leftEdgeInBounds
;
4201 startEdgeInBounds
= leftEdgeInBounds
;
4202 endEdgeInBounds
= rightEdgeInBounds
;
4205 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4208 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4211 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4214 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4218 // The other positioning values are all about being inside the container,
4219 // so in those cases all we care about is that any part of the container is visible.
4220 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4221 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4225 * Position the floatable below its container.
4227 * This should only be done when both of them are attached to the DOM and visible.
4231 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4232 if ( !this.positioning
) {
4237 // To continue, some things need to be true:
4238 // The element must actually be in the DOM
4239 this.isElementAttached() && (
4240 // The closest scrollable is the current window
4241 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4242 // OR is an element in the element's DOM
4243 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4246 // Abort early if important parts of the widget are no longer attached to the DOM
4250 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4251 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4254 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4257 if ( !this.needsCustomPosition
) {
4261 this.$floatable
.css( this.computePosition() );
4263 // We updated the position, so re-evaluate the clipping state.
4264 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4265 // will not notice the need to update itself.)
4266 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4267 // it not listen to the right events in the right places?
4276 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4277 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4278 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4280 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4282 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4283 var isBody
, scrollableX
, scrollableY
, containerPos
,
4284 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4285 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4286 direction
= this.$floatableContainer
.css( 'direction' ),
4287 $offsetParent
= this.$floatable
.offsetParent();
4289 if ( $offsetParent
.is( 'html' ) ) {
4290 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4291 // <html> element, but they do work on the <body>
4292 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4294 isBody
= $offsetParent
.is( 'body' );
4295 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4296 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4298 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4299 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4300 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4301 // or if it isn't scrollable
4302 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4303 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4305 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4306 // if the <body> has a margin
4307 containerPos
= isBody
?
4308 this.$floatableContainer
.offset() :
4309 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4310 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4311 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4312 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4313 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4315 if ( this.verticalPosition
=== 'below' ) {
4316 newPos
.top
= containerPos
.bottom
;
4317 } else if ( this.verticalPosition
=== 'above' ) {
4318 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4319 } else if ( this.verticalPosition
=== 'top' ) {
4320 newPos
.top
= containerPos
.top
;
4321 } else if ( this.verticalPosition
=== 'bottom' ) {
4322 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4323 } else if ( this.verticalPosition
=== 'center' ) {
4324 newPos
.top
= containerPos
.top
+
4325 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4328 if ( this.horizontalPosition
=== 'before' ) {
4329 newPos
.end
= containerPos
.start
;
4330 } else if ( this.horizontalPosition
=== 'after' ) {
4331 newPos
.start
= containerPos
.end
;
4332 } else if ( this.horizontalPosition
=== 'start' ) {
4333 newPos
.start
= containerPos
.start
;
4334 } else if ( this.horizontalPosition
=== 'end' ) {
4335 newPos
.end
= containerPos
.end
;
4336 } else if ( this.horizontalPosition
=== 'center' ) {
4337 newPos
.left
= containerPos
.left
+
4338 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4341 if ( newPos
.start
!== undefined ) {
4342 if ( direction
=== 'rtl' ) {
4343 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4345 newPos
.left
= newPos
.start
;
4347 delete newPos
.start
;
4349 if ( newPos
.end
!== undefined ) {
4350 if ( direction
=== 'rtl' ) {
4351 newPos
.left
= newPos
.end
;
4353 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4358 // Account for scroll position
4359 if ( newPos
.top
!== '' ) {
4360 newPos
.top
+= scrollTop
;
4362 if ( newPos
.bottom
!== '' ) {
4363 newPos
.bottom
-= scrollTop
;
4365 if ( newPos
.left
!== '' ) {
4366 newPos
.left
+= scrollLeft
;
4368 if ( newPos
.right
!== '' ) {
4369 newPos
.right
-= scrollLeft
;
4372 // Account for scrollbar gutter
4373 if ( newPos
.bottom
!== '' ) {
4374 newPos
.bottom
-= horizScrollbarHeight
;
4376 if ( direction
=== 'rtl' ) {
4377 if ( newPos
.left
!== '' ) {
4378 newPos
.left
-= vertScrollbarWidth
;
4381 if ( newPos
.right
!== '' ) {
4382 newPos
.right
-= vertScrollbarWidth
;
4390 * Element that can be automatically clipped to visible boundaries.
4392 * Whenever the element's natural height changes, you have to call
4393 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4394 * clipping correctly.
4396 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4397 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4398 * then #$clippable will be given a fixed reduced height and/or width and will be made
4399 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4400 * but you can build a static footer by setting #$clippableContainer to an element that contains
4401 * #$clippable and the footer.
4407 * @param {Object} [config] Configuration options
4408 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4409 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4410 * omit to use #$clippable
4412 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4413 // Configuration initialization
4414 config
= config
|| {};
4417 this.$clippable
= null;
4418 this.$clippableContainer
= null;
4419 this.clipping
= false;
4420 this.clippedHorizontally
= false;
4421 this.clippedVertically
= false;
4422 this.$clippableScrollableContainer
= null;
4423 this.$clippableScroller
= null;
4424 this.$clippableWindow
= null;
4425 this.idealWidth
= null;
4426 this.idealHeight
= null;
4427 this.onClippableScrollHandler
= this.clip
.bind( this );
4428 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4431 if ( config
.$clippableContainer
) {
4432 this.setClippableContainer( config
.$clippableContainer
);
4434 this.setClippableElement( config
.$clippable
|| this.$element
);
4440 * Set clippable element.
4442 * If an element is already set, it will be cleaned up before setting up the new element.
4444 * @param {jQuery} $clippable Element to make clippable
4446 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4447 if ( this.$clippable
) {
4448 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4449 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4450 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4453 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4458 * Set clippable container.
4460 * This is the container that will be measured when deciding whether to clip. When clipping,
4461 * #$clippable will be resized in order to keep the clippable container fully visible.
4463 * If the clippable container is unset, #$clippable will be used.
4465 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4467 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4468 this.$clippableContainer
= $clippableContainer
;
4469 if ( this.$clippable
) {
4477 * Do not turn clipping on until after the element is attached to the DOM and visible.
4479 * @param {boolean} [clipping] Enable clipping, omit to toggle
4482 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4483 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4485 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4486 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4487 this.warnedUnattached
= true;
4490 if ( this.clipping
!== clipping
) {
4491 this.clipping
= clipping
;
4493 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4494 // If the clippable container is the root, we have to listen to scroll events and check
4495 // jQuery.scrollTop on the window because of browser inconsistencies
4496 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4497 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4498 this.$clippableScrollableContainer
;
4499 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4500 this.$clippableWindow
= $( this.getElementWindow() )
4501 .on( 'resize', this.onClippableWindowResizeHandler
);
4502 // Initial clip after visible
4505 this.$clippable
.css( {
4513 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4515 this.$clippableScrollableContainer
= null;
4516 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4517 this.$clippableScroller
= null;
4518 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4519 this.$clippableWindow
= null;
4527 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4529 * @return {boolean} Element will be clipped to the visible area
4531 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4532 return this.clipping
;
4536 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4538 * @return {boolean} Part of the element is being clipped
4540 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4541 return this.clippedHorizontally
|| this.clippedVertically
;
4545 * Check if the right of the element is being clipped by the nearest scrollable container.
4547 * @return {boolean} Part of the element is being clipped
4549 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4550 return this.clippedHorizontally
;
4554 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4556 * @return {boolean} Part of the element is being clipped
4558 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4559 return this.clippedVertically
;
4563 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4565 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4566 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4568 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4569 this.idealWidth
= width
;
4570 this.idealHeight
= height
;
4572 if ( !this.clipping
) {
4573 // Update dimensions
4574 this.$clippable
.css( { width
: width
, height
: height
} );
4576 // While clipping, idealWidth and idealHeight are not considered
4580 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4581 * when the element's natural height changes.
4583 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4584 * overlapped by, the visible area of the nearest scrollable container.
4586 * Because calling clip() when the natural height changes isn't always possible, we also set
4587 * max-height when the element isn't being clipped. This means that if the element tries to grow
4588 * beyond the edge, something reasonable will happen before clip() is called.
4592 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4593 var $container
, extraHeight
, extraWidth
, ccOffset
,
4594 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4595 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4596 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4597 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4598 buffer
= 7; // Chosen by fair dice roll
4600 if ( !this.clipping
) {
4601 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4605 $container
= this.$clippableContainer
|| this.$clippable
;
4606 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4607 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4608 ccOffset
= $container
.offset();
4609 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4610 $scrollableContainer
= this.$clippableWindow
;
4611 scOffset
= { top
: 0, left
: 0 };
4613 $scrollableContainer
= this.$clippableScrollableContainer
;
4614 scOffset
= $scrollableContainer
.offset();
4616 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4617 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4618 ccWidth
= $container
.outerWidth() + buffer
;
4619 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4620 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4621 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4622 desiredWidth
= ccOffset
.left
< 0 ?
4623 ccWidth
+ ccOffset
.left
:
4624 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4625 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4626 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4627 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4628 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4629 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4630 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4631 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4632 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4633 clipWidth
= allotedWidth
< naturalWidth
;
4634 clipHeight
= allotedHeight
< naturalHeight
;
4637 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4638 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4639 this.$clippable
.css( 'overflowX', 'scroll' );
4640 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4641 this.$clippable
.css( {
4642 width
: Math
.max( 0, allotedWidth
),
4646 this.$clippable
.css( {
4648 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4649 maxWidth
: Math
.max( 0, allotedWidth
)
4653 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4654 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4655 this.$clippable
.css( 'overflowY', 'scroll' );
4656 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4657 this.$clippable
.css( {
4658 height
: Math
.max( 0, allotedHeight
),
4662 this.$clippable
.css( {
4664 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4665 maxHeight
: Math
.max( 0, allotedHeight
)
4669 // If we stopped clipping in at least one of the dimensions
4670 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4671 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4674 this.clippedHorizontally
= clipWidth
;
4675 this.clippedVertically
= clipHeight
;
4681 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4682 * By default, each popup has an anchor that points toward its origin.
4683 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4685 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4688 * // A popup widget.
4689 * var popup = new OO.ui.PopupWidget( {
4690 * $content: $( '<p>Hi there!</p>' ),
4695 * $( 'body' ).append( popup.$element );
4696 * // To display the popup, toggle the visibility to 'true'.
4697 * popup.toggle( true );
4699 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4702 * @extends OO.ui.Widget
4703 * @mixins OO.ui.mixin.LabelElement
4704 * @mixins OO.ui.mixin.ClippableElement
4705 * @mixins OO.ui.mixin.FloatableElement
4708 * @param {Object} [config] Configuration options
4709 * @cfg {number} [width=320] Width of popup in pixels
4710 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4711 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4712 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4713 * 'above': Put popup above $floatableContainer; anchor points down to the start edge of $floatableContainer
4714 * 'below': Put popup below $floatableContainer; anchor points up to the start edge of $floatableContainer
4715 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4716 * endwards (right/left) to the vertical center of $floatableContainer
4717 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4718 * startwards (left/right) to the vertical center of $floatableContainer
4719 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4720 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4721 * as possible while still keeping the anchor within the popup;
4722 * if position is before/after, move the popup as far downwards as possible.
4723 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4724 * as possible while still keeping the anchor within the popup;
4725 * if position in before/after, move the popup as far upwards as possible.
4726 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4727 * of the popup with the center of $floatableContainer.
4728 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4729 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4730 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4731 * See the [OOjs UI docs on MediaWiki][3] for an example.
4732 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4733 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4734 * @cfg {jQuery} [$content] Content to append to the popup's body
4735 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4736 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4737 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4738 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4740 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4741 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4743 * @cfg {boolean} [padded=false] Add padding to the popup's body
4745 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4746 // Configuration initialization
4747 config
= config
|| {};
4749 // Parent constructor
4750 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4752 // Properties (must be set before ClippableElement constructor call)
4753 this.$body
= $( '<div>' );
4754 this.$popup
= $( '<div>' );
4756 // Mixin constructors
4757 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4758 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4759 $clippable
: this.$body
,
4760 $clippableContainer
: this.$popup
4762 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4765 this.$anchor
= $( '<div>' );
4766 // If undefined, will be computed lazily in updateDimensions()
4767 this.$container
= config
.$container
;
4768 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4769 this.autoClose
= !!config
.autoClose
;
4770 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4771 this.transitionTimeout
= null;
4772 this.anchored
= false;
4773 this.width
= config
.width
!== undefined ? config
.width
: 320;
4774 this.height
= config
.height
!== undefined ? config
.height
: null;
4775 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4776 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4779 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4780 this.setAlignment( config
.align
|| 'center' );
4781 this.setPosition( config
.position
|| 'below' );
4782 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4783 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4785 .addClass( 'oo-ui-popupWidget-popup' )
4786 .append( this.$body
);
4788 .addClass( 'oo-ui-popupWidget' )
4789 .append( this.$popup
, this.$anchor
);
4790 // Move content, which was added to #$element by OO.ui.Widget, to the body
4791 // FIXME This is gross, we should use '$body' or something for the config
4792 if ( config
.$content
instanceof jQuery
) {
4793 this.$body
.append( config
.$content
);
4796 if ( config
.padded
) {
4797 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4800 if ( config
.head
) {
4801 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4802 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4803 this.$head
= $( '<div>' )
4804 .addClass( 'oo-ui-popupWidget-head' )
4805 .append( this.$label
, this.closeButton
.$element
);
4806 this.$popup
.prepend( this.$head
);
4809 if ( config
.$footer
) {
4810 this.$footer
= $( '<div>' )
4811 .addClass( 'oo-ui-popupWidget-footer' )
4812 .append( config
.$footer
);
4813 this.$popup
.append( this.$footer
);
4816 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4817 // that reference properties not initialized at that time of parent class construction
4818 // TODO: Find a better way to handle post-constructor setup
4819 this.visible
= false;
4820 this.$element
.addClass( 'oo-ui-element-hidden' );
4825 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4826 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4827 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4828 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4835 * The popup is ready: it is visible and has been positioned and clipped.
4841 * Handles mouse down events.
4844 * @param {MouseEvent} e Mouse down event
4846 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4849 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4851 this.toggle( false );
4856 * Bind mouse down listener.
4860 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4861 // Capture clicks outside popup
4862 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4866 * Handles close button click events.
4870 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4871 if ( this.isVisible() ) {
4872 this.toggle( false );
4877 * Unbind mouse down listener.
4881 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4882 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4886 * Handles key down events.
4889 * @param {KeyboardEvent} e Key down event
4891 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4893 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4896 this.toggle( false );
4898 e
.stopPropagation();
4903 * Bind key down listener.
4907 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4908 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4912 * Unbind key down listener.
4916 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4917 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4921 * Show, hide, or toggle the visibility of the anchor.
4923 * @param {boolean} [show] Show anchor, omit to toggle
4925 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4926 show
= show
=== undefined ? !this.anchored
: !!show
;
4928 if ( this.anchored
!== show
) {
4930 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4932 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4934 this.anchored
= show
;
4938 * Change which edge the anchor appears on.
4940 * @param {string} edge 'top', 'bottom', 'start' or 'end'
4942 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
4943 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
4944 throw new Error( 'Invalid value for edge: ' + edge
);
4946 if ( this.anchorEdge
!== null ) {
4947 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
4949 this.anchorEdge
= edge
;
4950 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
4954 * Check if the anchor is visible.
4956 * @return {boolean} Anchor is visible
4958 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4959 return this.anchored
;
4963 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
4964 * `.toggle( true )` after its #$element is attached to the DOM.
4966 * Do not show the popup while it is not attached to the DOM. The calculations required to display
4967 * it in the right place and with the right dimensions only work correctly while it is attached.
4968 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
4969 * strictly enforced, so currently it only generates a warning in the browser console.
4974 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4976 show
= show
=== undefined ? !this.isVisible() : !!show
;
4978 change
= show
!== this.isVisible();
4980 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4981 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
4982 this.warnedUnattached
= true;
4984 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
4985 // Fall back to the parent node if the floatableContainer is not set
4986 this.setFloatableContainer( this.$element
.parent() );
4990 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4993 this.togglePositioning( show
&& !!this.$floatableContainer
);
4996 if ( this.autoClose
) {
4997 this.bindMouseDownListener();
4998 this.bindKeyDownListener();
5000 this.updateDimensions();
5001 this.toggleClipping( true );
5002 this.emit( 'ready' );
5004 this.toggleClipping( false );
5005 if ( this.autoClose
) {
5006 this.unbindMouseDownListener();
5007 this.unbindKeyDownListener();
5016 * Set the size of the popup.
5018 * Changing the size may also change the popup's position depending on the alignment.
5020 * @param {number} width Width in pixels
5021 * @param {number} height Height in pixels
5022 * @param {boolean} [transition=false] Use a smooth transition
5025 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5027 this.height
= height
!== undefined ? height
: null;
5028 if ( this.isVisible() ) {
5029 this.updateDimensions( transition
);
5034 * Update the size and position.
5036 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5037 * be called automatically.
5039 * @param {boolean} [transition=false] Use a smooth transition
5042 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5045 // Prevent transition from being interrupted
5046 clearTimeout( this.transitionTimeout
);
5048 // Enable transition
5049 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5055 // Prevent transitioning after transition is complete
5056 this.transitionTimeout
= setTimeout( function () {
5057 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5060 // Prevent transitioning immediately
5061 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5068 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5069 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5070 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5071 offsetParentPos
, containerPos
,
5073 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5076 'force-left': 'backwards',
5077 'force-right': 'forwards'
5080 'force-left': 'forwards',
5081 'force-right': 'backwards'
5101 if ( !this.$container
) {
5102 // Lazy-initialize $container if not specified in constructor
5103 this.$container
= $( this.getClosestScrollableElementContainer() );
5105 direction
= this.$container
.css( 'direction' );
5107 // Set height and width before we do anything else, since it might cause our measurements
5108 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5111 height
: this.height
!== null ? this.height
: 'auto'
5114 align
= alignMap
[ direction
][ this.align
] || this.align
;
5115 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5116 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5117 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5118 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5119 near
= vertical
? 'top' : 'left';
5120 far
= vertical
? 'bottom' : 'right';
5121 sizeProp
= vertical
? 'Height' : 'Width';
5122 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5124 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5125 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5126 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5129 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5130 // Find out which property FloatableElement used for positioning, and adjust that value
5131 positionProp
= vertical
?
5132 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5133 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5135 // Figure out where the near and far edges of the popup and $floatableContainer are
5136 floatablePos
= this.$floatableContainer
.offset();
5137 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5138 // Measure where the offsetParent is and compute our position based on that and parentPosition
5139 offsetParentPos
= this.$element
.offsetParent().offset();
5141 if ( positionProp
=== near
) {
5142 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5143 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5145 popupPos
[ far
] = offsetParentPos
[ near
] +
5146 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5147 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5150 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5151 // For popups above/below, we point to the start edge; for popups before/after, we point to the center
5152 anchorPos
= vertical
? ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2 : floatablePos
[ start
];
5153 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5155 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5156 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5157 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5158 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5159 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5160 // Not enough space for the anchor on the start side; pull the popup startwards
5161 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5162 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5163 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5164 // Not enough space for the anchor on the end side; pull the popup endwards
5165 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5166 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5168 positionAdjustment
= 0;
5171 // Check if the popup will go beyond the edge of this.$container
5172 containerPos
= this.$container
.offset();
5173 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5174 // Take into account how much the popup will move because of the adjustments we're going to make
5175 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5176 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5177 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5178 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5179 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5180 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5181 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5182 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5183 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5184 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5187 // Adjust anchorOffset for positionAdjustment
5188 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5190 // Position the anchor
5191 anchorCss
[ start
] = anchorOffset
;
5192 this.$anchor
.css( anchorCss
);
5193 // Move the popup if needed
5194 parentPosition
[ positionProp
] += positionAdjustment
;
5196 return parentPosition
;
5200 * Set popup alignment
5202 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5203 * `backwards` or `forwards`.
5205 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5206 // Validate alignment
5207 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5210 this.align
= 'center';
5216 * Get popup alignment
5218 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5219 * `backwards` or `forwards`.
5221 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5226 * Change the positioning of the popup.
5228 * @param {string} position 'above', 'below', 'before' or 'after'
5230 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5231 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5234 this.popupPosition
= position
;
5239 * Get popup positioning.
5241 * @return {string} 'above', 'below', 'before' or 'after'
5243 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5244 return this.popupPosition
;
5248 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5249 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5250 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5251 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5257 * @param {Object} [config] Configuration options
5258 * @cfg {Object} [popup] Configuration to pass to popup
5259 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5261 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5262 // Configuration initialization
5263 config
= config
|| {};
5266 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5269 $floatableContainer
: this.$element
5273 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5283 * @return {OO.ui.PopupWidget} Popup widget
5285 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5290 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5291 * which is used to display additional information or options.
5294 * // Example of a popup button.
5295 * var popupButton = new OO.ui.PopupButtonWidget( {
5296 * label: 'Popup button with options',
5299 * $content: $( '<p>Additional options here.</p>' ),
5301 * align: 'force-left'
5304 * // Append the button to the DOM.
5305 * $( 'body' ).append( popupButton.$element );
5308 * @extends OO.ui.ButtonWidget
5309 * @mixins OO.ui.mixin.PopupElement
5312 * @param {Object} [config] Configuration options
5313 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5314 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5315 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5317 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5318 // Parent constructor
5319 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5321 // Mixin constructors
5322 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5325 this.$overlay
= config
.$overlay
|| this.$element
;
5328 this.connect( this, { click
: 'onAction' } );
5332 .addClass( 'oo-ui-popupButtonWidget' )
5333 .attr( 'aria-haspopup', 'true' );
5335 .addClass( 'oo-ui-popupButtonWidget-popup' )
5336 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5337 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5338 this.$overlay
.append( this.popup
.$element
);
5343 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5344 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5349 * Handle the button action being triggered.
5353 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5354 this.popup
.toggle();
5358 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5360 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5365 * @mixins OO.ui.mixin.GroupElement
5368 * @param {Object} [config] Configuration options
5370 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5371 // Mixin constructors
5372 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5377 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5382 * Set the disabled state of the widget.
5384 * This will also update the disabled state of child widgets.
5386 * @param {boolean} disabled Disable widget
5389 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5393 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5394 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5396 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5398 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5399 this.items
[ i
].updateDisabled();
5407 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5409 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5410 * allows bidirectional communication.
5412 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5420 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5427 * Check if widget is disabled.
5429 * Checks parent if present, making disabled state inheritable.
5431 * @return {boolean} Widget is disabled
5433 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5434 return this.disabled
||
5435 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5439 * Set group element is in.
5441 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5444 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5446 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5447 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5449 // Initialize item disabled states
5450 this.updateDisabled();
5456 * OptionWidgets are special elements that can be selected and configured with data. The
5457 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5458 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5459 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5461 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5464 * @extends OO.ui.Widget
5465 * @mixins OO.ui.mixin.ItemWidget
5466 * @mixins OO.ui.mixin.LabelElement
5467 * @mixins OO.ui.mixin.FlaggedElement
5468 * @mixins OO.ui.mixin.AccessKeyedElement
5471 * @param {Object} [config] Configuration options
5473 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5474 // Configuration initialization
5475 config
= config
|| {};
5477 // Parent constructor
5478 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5480 // Mixin constructors
5481 OO
.ui
.mixin
.ItemWidget
.call( this );
5482 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5483 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5484 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5487 this.selected
= false;
5488 this.highlighted
= false;
5489 this.pressed
= false;
5493 .data( 'oo-ui-optionWidget', this )
5494 // Allow programmatic focussing (and by accesskey), but not tabbing
5495 .attr( 'tabindex', '-1' )
5496 .attr( 'role', 'option' )
5497 .attr( 'aria-selected', 'false' )
5498 .addClass( 'oo-ui-optionWidget' )
5499 .append( this.$label
);
5504 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5505 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5506 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5507 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5508 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5510 /* Static Properties */
5513 * Whether this option can be selected. See #setSelected.
5517 * @property {boolean}
5519 OO
.ui
.OptionWidget
.static.selectable
= true;
5522 * Whether this option can be highlighted. See #setHighlighted.
5526 * @property {boolean}
5528 OO
.ui
.OptionWidget
.static.highlightable
= true;
5531 * Whether this option can be pressed. See #setPressed.
5535 * @property {boolean}
5537 OO
.ui
.OptionWidget
.static.pressable
= true;
5540 * Whether this option will be scrolled into view when it is selected.
5544 * @property {boolean}
5546 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5551 * Check if the option can be selected.
5553 * @return {boolean} Item is selectable
5555 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5556 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5560 * Check if the option can be highlighted. A highlight indicates that the option
5561 * may be selected when a user presses enter or clicks. Disabled items cannot
5564 * @return {boolean} Item is highlightable
5566 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5567 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5571 * Check if the option can be pressed. The pressed state occurs when a user mouses
5572 * down on an item, but has not yet let go of the mouse.
5574 * @return {boolean} Item is pressable
5576 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5577 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5581 * Check if the option is selected.
5583 * @return {boolean} Item is selected
5585 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5586 return this.selected
;
5590 * Check if the option is highlighted. A highlight indicates that the
5591 * item may be selected when a user presses enter or clicks.
5593 * @return {boolean} Item is highlighted
5595 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5596 return this.highlighted
;
5600 * Check if the option is pressed. The pressed state occurs when a user mouses
5601 * down on an item, but has not yet let go of the mouse. The item may appear
5602 * selected, but it will not be selected until the user releases the mouse.
5604 * @return {boolean} Item is pressed
5606 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5607 return this.pressed
;
5611 * Set the option’s selected state. In general, all modifications to the selection
5612 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5613 * method instead of this method.
5615 * @param {boolean} [state=false] Select option
5618 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5619 if ( this.constructor.static.selectable
) {
5620 this.selected
= !!state
;
5622 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5623 .attr( 'aria-selected', state
.toString() );
5624 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5625 this.scrollElementIntoView();
5627 this.updateThemeClasses();
5633 * Set the option’s highlighted state. In general, all programmatic
5634 * modifications to the highlight should be handled by the
5635 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5636 * method instead of this method.
5638 * @param {boolean} [state=false] Highlight option
5641 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5642 if ( this.constructor.static.highlightable
) {
5643 this.highlighted
= !!state
;
5644 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5645 this.updateThemeClasses();
5651 * Set the option’s pressed state. In general, all
5652 * programmatic modifications to the pressed state should be handled by the
5653 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5654 * method instead of this method.
5656 * @param {boolean} [state=false] Press option
5659 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5660 if ( this.constructor.static.pressable
) {
5661 this.pressed
= !!state
;
5662 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5663 this.updateThemeClasses();
5669 * Get text to match search strings against.
5671 * The default implementation returns the label text, but subclasses
5672 * can override this to provide more complex behavior.
5674 * @return {string|boolean} String to match search string against
5676 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5677 var label
= this.getLabel();
5678 return typeof label
=== 'string' ? label
: this.$label
.text();
5682 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5683 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5684 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5687 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5688 * information, please see the [OOjs UI documentation on MediaWiki][1].
5691 * // Example of a select widget with three options
5692 * var select = new OO.ui.SelectWidget( {
5694 * new OO.ui.OptionWidget( {
5696 * label: 'Option One',
5698 * new OO.ui.OptionWidget( {
5700 * label: 'Option Two',
5702 * new OO.ui.OptionWidget( {
5704 * label: 'Option Three',
5708 * $( 'body' ).append( select.$element );
5710 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5714 * @extends OO.ui.Widget
5715 * @mixins OO.ui.mixin.GroupWidget
5718 * @param {Object} [config] Configuration options
5719 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5720 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5721 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5722 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5724 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5725 // Configuration initialization
5726 config
= config
|| {};
5728 // Parent constructor
5729 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5731 // Mixin constructors
5732 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5735 this.pressed
= false;
5736 this.selecting
= null;
5737 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5738 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5739 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5740 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5741 this.keyPressBuffer
= '';
5742 this.keyPressBufferTimer
= null;
5743 this.blockMouseOverEvents
= 0;
5746 this.connect( this, {
5750 focusin
: this.onFocus
.bind( this ),
5751 mousedown
: this.onMouseDown
.bind( this ),
5752 mouseover
: this.onMouseOver
.bind( this ),
5753 mouseleave
: this.onMouseLeave
.bind( this )
5758 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5759 .attr( 'role', 'listbox' );
5760 if ( Array
.isArray( config
.items
) ) {
5761 this.addItems( config
.items
);
5767 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5768 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5775 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5777 * @param {OO.ui.OptionWidget|null} item Highlighted item
5783 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5784 * pressed state of an option.
5786 * @param {OO.ui.OptionWidget|null} item Pressed item
5792 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5794 * @param {OO.ui.OptionWidget|null} item Selected item
5799 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5800 * @param {OO.ui.OptionWidget} item Chosen item
5806 * An `add` event is emitted when options are added to the select with the #addItems method.
5808 * @param {OO.ui.OptionWidget[]} items Added items
5809 * @param {number} index Index of insertion point
5815 * A `remove` event is emitted when options are removed from the select with the #clearItems
5816 * or #removeItems methods.
5818 * @param {OO.ui.OptionWidget[]} items Removed items
5824 * Handle focus events
5827 * @param {jQuery.Event} event
5829 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5831 if ( event
.target
=== this.$element
[ 0 ] ) {
5832 // This widget was focussed, e.g. by the user tabbing to it.
5833 // The styles for focus state depend on one of the items being selected.
5834 if ( !this.getSelectedItem() ) {
5835 item
= this.getFirstSelectableItem();
5838 // One of the options got focussed (and the event bubbled up here).
5839 // They can't be tabbed to, but they can be activated using accesskeys.
5840 item
= this.getTargetItem( event
);
5844 if ( item
.constructor.static.highlightable
) {
5845 this.highlightItem( item
);
5847 this.selectItem( item
);
5851 if ( event
.target
!== this.$element
[ 0 ] ) {
5852 this.$element
.focus();
5857 * Handle mouse down events.
5860 * @param {jQuery.Event} e Mouse down event
5862 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5865 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5866 this.togglePressed( true );
5867 item
= this.getTargetItem( e
);
5868 if ( item
&& item
.isSelectable() ) {
5869 this.pressItem( item
);
5870 this.selecting
= item
;
5871 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5872 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5879 * Handle mouse up events.
5882 * @param {MouseEvent} e Mouse up event
5884 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5887 this.togglePressed( false );
5888 if ( !this.selecting
) {
5889 item
= this.getTargetItem( e
);
5890 if ( item
&& item
.isSelectable() ) {
5891 this.selecting
= item
;
5894 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5895 this.pressItem( null );
5896 this.chooseItem( this.selecting
);
5897 this.selecting
= null;
5900 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5901 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5907 * Handle mouse move events.
5910 * @param {MouseEvent} e Mouse move event
5912 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5915 if ( !this.isDisabled() && this.pressed
) {
5916 item
= this.getTargetItem( e
);
5917 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5918 this.pressItem( item
);
5919 this.selecting
= item
;
5925 * Handle mouse over events.
5928 * @param {jQuery.Event} e Mouse over event
5930 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5932 if ( this.blockMouseOverEvents
) {
5935 if ( !this.isDisabled() ) {
5936 item
= this.getTargetItem( e
);
5937 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5943 * Handle mouse leave events.
5946 * @param {jQuery.Event} e Mouse over event
5948 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5949 if ( !this.isDisabled() ) {
5950 this.highlightItem( null );
5956 * Handle key down events.
5959 * @param {KeyboardEvent} e Key down event
5961 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5964 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5966 if ( !this.isDisabled() && this.isVisible() ) {
5967 switch ( e
.keyCode
) {
5968 case OO
.ui
.Keys
.ENTER
:
5969 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5970 // Was only highlighted, now let's select it. No-op if already selected.
5971 this.chooseItem( currentItem
);
5976 case OO
.ui
.Keys
.LEFT
:
5977 this.clearKeyPressBuffer();
5978 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5981 case OO
.ui
.Keys
.DOWN
:
5982 case OO
.ui
.Keys
.RIGHT
:
5983 this.clearKeyPressBuffer();
5984 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5987 case OO
.ui
.Keys
.ESCAPE
:
5988 case OO
.ui
.Keys
.TAB
:
5989 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5990 currentItem
.setHighlighted( false );
5992 this.unbindKeyDownListener();
5993 this.unbindKeyPressListener();
5994 // Don't prevent tabbing away / defocusing
6000 if ( nextItem
.constructor.static.highlightable
) {
6001 this.highlightItem( nextItem
);
6003 this.chooseItem( nextItem
);
6005 this.scrollItemIntoView( nextItem
);
6010 e
.stopPropagation();
6016 * Bind key down listener.
6020 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6021 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6025 * Unbind key down listener.
6029 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6030 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6034 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6036 * @param {OO.ui.OptionWidget} item Item to scroll into view
6038 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6040 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6041 // and around 100-150 ms after it is finished.
6042 this.blockMouseOverEvents
++;
6043 item
.scrollElementIntoView().done( function () {
6044 setTimeout( function () {
6045 widget
.blockMouseOverEvents
--;
6051 * Clear the key-press buffer
6055 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6056 if ( this.keyPressBufferTimer
) {
6057 clearTimeout( this.keyPressBufferTimer
);
6058 this.keyPressBufferTimer
= null;
6060 this.keyPressBuffer
= '';
6064 * Handle key press events.
6067 * @param {KeyboardEvent} e Key press event
6069 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6070 var c
, filter
, item
;
6072 if ( !e
.charCode
) {
6073 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6074 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6079 if ( String
.fromCodePoint
) {
6080 c
= String
.fromCodePoint( e
.charCode
);
6082 c
= String
.fromCharCode( e
.charCode
);
6085 if ( this.keyPressBufferTimer
) {
6086 clearTimeout( this.keyPressBufferTimer
);
6088 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6090 item
= this.getHighlightedItem() || this.getSelectedItem();
6092 if ( this.keyPressBuffer
=== c
) {
6093 // Common (if weird) special case: typing "xxxx" will cycle through all
6094 // the items beginning with "x".
6096 item
= this.getRelativeSelectableItem( item
, 1 );
6099 this.keyPressBuffer
+= c
;
6102 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6103 if ( !item
|| !filter( item
) ) {
6104 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6107 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6108 this.highlightItem( item
);
6110 this.chooseItem( item
);
6112 this.scrollItemIntoView( item
);
6116 e
.stopPropagation();
6120 * Get a matcher for the specific string
6123 * @param {string} s String to match against items
6124 * @param {boolean} [exact=false] Only accept exact matches
6125 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6127 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6130 if ( s
.normalize
) {
6133 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6134 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6138 re
= new RegExp( re
, 'i' );
6139 return function ( item
) {
6140 var matchText
= item
.getMatchText();
6141 if ( matchText
.normalize
) {
6142 matchText
= matchText
.normalize();
6144 return re
.test( matchText
);
6149 * Bind key press listener.
6153 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6154 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6158 * Unbind key down listener.
6160 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6165 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6166 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6167 this.clearKeyPressBuffer();
6171 * Visibility change handler
6174 * @param {boolean} visible
6176 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6178 this.clearKeyPressBuffer();
6183 * Get the closest item to a jQuery.Event.
6186 * @param {jQuery.Event} e
6187 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6189 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6190 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6194 * Get selected item.
6196 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6198 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6201 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6202 if ( this.items
[ i
].isSelected() ) {
6203 return this.items
[ i
];
6210 * Get highlighted item.
6212 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6214 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6217 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6218 if ( this.items
[ i
].isHighlighted() ) {
6219 return this.items
[ i
];
6226 * Toggle pressed state.
6228 * Press is a state that occurs when a user mouses down on an item, but
6229 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6230 * until the user releases the mouse.
6232 * @param {boolean} pressed An option is being pressed
6234 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6235 if ( pressed
=== undefined ) {
6236 pressed
= !this.pressed
;
6238 if ( pressed
!== this.pressed
) {
6240 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6241 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6242 this.pressed
= pressed
;
6247 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6248 * and any existing highlight will be removed. The highlight is mutually exclusive.
6250 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6254 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6255 var i
, len
, highlighted
,
6258 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6259 highlighted
= this.items
[ i
] === item
;
6260 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6261 this.items
[ i
].setHighlighted( highlighted
);
6266 this.emit( 'highlight', item
);
6273 * Fetch an item by its label.
6275 * @param {string} label Label of the item to select.
6276 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6277 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6279 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6281 len
= this.items
.length
,
6282 filter
= this.getItemMatcher( label
, true );
6284 for ( i
= 0; i
< len
; i
++ ) {
6285 item
= this.items
[ i
];
6286 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6293 filter
= this.getItemMatcher( label
, false );
6294 for ( i
= 0; i
< len
; i
++ ) {
6295 item
= this.items
[ i
];
6296 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6312 * Programmatically select an option by its label. If the item does not exist,
6313 * all options will be deselected.
6315 * @param {string} [label] Label of the item to select.
6316 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6320 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6321 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6322 if ( label
=== undefined || !itemFromLabel
) {
6323 return this.selectItem();
6325 return this.selectItem( itemFromLabel
);
6329 * Programmatically select an option by its data. If the `data` parameter is omitted,
6330 * or if the item does not exist, all options will be deselected.
6332 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6336 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6337 var itemFromData
= this.getItemFromData( data
);
6338 if ( data
=== undefined || !itemFromData
) {
6339 return this.selectItem();
6341 return this.selectItem( itemFromData
);
6345 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6346 * all options will be deselected.
6348 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6352 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6353 var i
, len
, selected
,
6356 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6357 selected
= this.items
[ i
] === item
;
6358 if ( this.items
[ i
].isSelected() !== selected
) {
6359 this.items
[ i
].setSelected( selected
);
6364 this.emit( 'select', item
);
6373 * Press is a state that occurs when a user mouses down on an item, but has not
6374 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6375 * releases the mouse.
6377 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6381 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6382 var i
, len
, pressed
,
6385 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6386 pressed
= this.items
[ i
] === item
;
6387 if ( this.items
[ i
].isPressed() !== pressed
) {
6388 this.items
[ i
].setPressed( pressed
);
6393 this.emit( 'press', item
);
6402 * Note that ‘choose’ should never be modified programmatically. A user can choose
6403 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6404 * use the #selectItem method.
6406 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6407 * when users choose an item with the keyboard or mouse.
6409 * @param {OO.ui.OptionWidget} item Item to choose
6413 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6415 this.selectItem( item
);
6416 this.emit( 'choose', item
);
6423 * Get an option by its position relative to the specified item (or to the start of the option array,
6424 * if item is `null`). The direction in which to search through the option array is specified with a
6425 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6426 * `null` if there are no options in the array.
6428 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6429 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6430 * @param {Function} [filter] Only consider items for which this function returns
6431 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6432 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6434 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6435 var currentIndex
, nextIndex
, i
,
6436 increase
= direction
> 0 ? 1 : -1,
6437 len
= this.items
.length
;
6439 if ( item
instanceof OO
.ui
.OptionWidget
) {
6440 currentIndex
= this.items
.indexOf( item
);
6441 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6443 // If no item is selected and moving forward, start at the beginning.
6444 // If moving backward, start at the end.
6445 nextIndex
= direction
> 0 ? 0 : len
- 1;
6448 for ( i
= 0; i
< len
; i
++ ) {
6449 item
= this.items
[ nextIndex
];
6451 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6452 ( !filter
|| filter( item
) )
6456 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6462 * Get the next selectable item or `null` if there are no selectable items.
6463 * Disabled options and menu-section markers and breaks are not selectable.
6465 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6467 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6468 return this.getRelativeSelectableItem( null, 1 );
6472 * Add an array of options to the select. Optionally, an index number can be used to
6473 * specify an insertion point.
6475 * @param {OO.ui.OptionWidget[]} items Items to add
6476 * @param {number} [index] Index to insert items after
6480 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6482 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6484 // Always provide an index, even if it was omitted
6485 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6491 * Remove the specified array of options from the select. Options will be detached
6492 * from the DOM, not removed, so they can be reused later. To remove all options from
6493 * the select, you may wish to use the #clearItems method instead.
6495 * @param {OO.ui.OptionWidget[]} items Items to remove
6499 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6502 // Deselect items being removed
6503 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6505 if ( item
.isSelected() ) {
6506 this.selectItem( null );
6511 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6513 this.emit( 'remove', items
);
6519 * Clear all options from the select. Options will be detached from the DOM, not removed,
6520 * so that they can be reused later. To remove a subset of options from the select, use
6521 * the #removeItems method.
6526 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6527 var items
= this.items
.slice();
6530 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6533 this.selectItem( null );
6535 this.emit( 'remove', items
);
6541 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6542 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6543 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6544 * options. For more information about options and selects, please see the
6545 * [OOjs UI documentation on MediaWiki][1].
6548 * // Decorated options in a select widget
6549 * var select = new OO.ui.SelectWidget( {
6551 * new OO.ui.DecoratedOptionWidget( {
6553 * label: 'Option with icon',
6556 * new OO.ui.DecoratedOptionWidget( {
6558 * label: 'Option with indicator',
6563 * $( 'body' ).append( select.$element );
6565 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6568 * @extends OO.ui.OptionWidget
6569 * @mixins OO.ui.mixin.IconElement
6570 * @mixins OO.ui.mixin.IndicatorElement
6573 * @param {Object} [config] Configuration options
6575 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6576 // Parent constructor
6577 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6579 // Mixin constructors
6580 OO
.ui
.mixin
.IconElement
.call( this, config
);
6581 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6585 .addClass( 'oo-ui-decoratedOptionWidget' )
6586 .prepend( this.$icon
)
6587 .append( this.$indicator
);
6592 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6593 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6594 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6597 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6598 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6599 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6601 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6604 * @extends OO.ui.DecoratedOptionWidget
6607 * @param {Object} [config] Configuration options
6609 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6610 // Configuration initialization
6611 config
= $.extend( { icon
: 'check' }, config
);
6613 // Parent constructor
6614 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6618 .attr( 'role', 'menuitem' )
6619 .addClass( 'oo-ui-menuOptionWidget' );
6624 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6626 /* Static Properties */
6632 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6635 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6636 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6639 * var myDropdown = new OO.ui.DropdownWidget( {
6642 * new OO.ui.MenuSectionOptionWidget( {
6645 * new OO.ui.MenuOptionWidget( {
6647 * label: 'Welsh Corgi'
6649 * new OO.ui.MenuOptionWidget( {
6651 * label: 'Standard Poodle'
6653 * new OO.ui.MenuSectionOptionWidget( {
6656 * new OO.ui.MenuOptionWidget( {
6663 * $( 'body' ).append( myDropdown.$element );
6666 * @extends OO.ui.DecoratedOptionWidget
6669 * @param {Object} [config] Configuration options
6671 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6672 // Parent constructor
6673 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6676 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6677 .attr( 'role', '' );
6682 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6684 /* Static Properties */
6690 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6696 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6699 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6700 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6701 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6702 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6703 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6704 * and customized to be opened, closed, and displayed as needed.
6706 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6707 * mouse outside the menu.
6709 * Menus also have support for keyboard interaction:
6711 * - Enter/Return key: choose and select a menu option
6712 * - Up-arrow key: highlight the previous menu option
6713 * - Down-arrow key: highlight the next menu option
6714 * - Esc key: hide the menu
6716 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6718 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6719 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6722 * @extends OO.ui.SelectWidget
6723 * @mixins OO.ui.mixin.ClippableElement
6726 * @param {Object} [config] Configuration options
6727 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6728 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6729 * and {@link OO.ui.mixin.LookupElement LookupElement}
6730 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6731 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6732 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6733 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6734 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6735 * that button, unless the button (or its parent widget) is passed in here.
6736 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6737 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6738 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6740 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6741 // Configuration initialization
6742 config
= config
|| {};
6744 // Parent constructor
6745 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6747 // Mixin constructors
6748 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6751 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6752 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6753 this.filterFromInput
= !!config
.filterFromInput
;
6754 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6755 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6756 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6757 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6761 .addClass( 'oo-ui-menuSelectWidget' )
6762 .attr( 'role', 'menu' );
6764 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6765 // that reference properties not initialized at that time of parent class construction
6766 // TODO: Find a better way to handle post-constructor setup
6767 this.visible
= false;
6768 this.$element
.addClass( 'oo-ui-element-hidden' );
6773 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6774 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6779 * Handles document mouse down events.
6782 * @param {MouseEvent} e Mouse down event
6784 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6786 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6787 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6789 this.toggle( false );
6796 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6797 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6799 if ( !this.isDisabled() && this.isVisible() ) {
6800 switch ( e
.keyCode
) {
6801 case OO
.ui
.Keys
.LEFT
:
6802 case OO
.ui
.Keys
.RIGHT
:
6803 // Do nothing if a text field is associated, arrow keys will be handled natively
6804 if ( !this.$input
) {
6805 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6808 case OO
.ui
.Keys
.ESCAPE
:
6809 case OO
.ui
.Keys
.TAB
:
6810 if ( currentItem
) {
6811 currentItem
.setHighlighted( false );
6813 this.toggle( false );
6814 // Don't prevent tabbing away, prevent defocusing
6815 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6817 e
.stopPropagation();
6821 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6828 * Update menu item visibility after input changes.
6832 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6833 var i
, item
, visible
, section
, sectionEmpty
,
6835 len
= this.items
.length
,
6836 showAll
= !this.isVisible(),
6837 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6839 // Hide non-matching options, and also hide section headers if all options
6840 // in their section are hidden.
6841 for ( i
= 0; i
< len
; i
++ ) {
6842 item
= this.items
[ i
];
6843 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
6845 // If the previous section was empty, hide its header
6846 section
.toggle( showAll
|| !sectionEmpty
);
6849 sectionEmpty
= true;
6850 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
6851 visible
= showAll
|| filter( item
);
6852 anyVisible
= anyVisible
|| visible
;
6853 sectionEmpty
= sectionEmpty
&& !visible
;
6854 item
.toggle( visible
);
6857 // Process the final section
6859 section
.toggle( showAll
|| !sectionEmpty
);
6862 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6864 // Reevaluate clipping
6871 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6872 if ( this.$input
) {
6873 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6875 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6882 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6883 if ( this.$input
) {
6884 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6886 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6893 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6894 if ( this.$input
) {
6895 if ( this.filterFromInput
) {
6896 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6899 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6906 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6907 if ( this.$input
) {
6908 if ( this.filterFromInput
) {
6909 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6910 this.updateItemVisibility();
6913 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6920 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
6922 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6923 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6925 * @param {OO.ui.OptionWidget} item Item to choose
6928 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6929 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6930 if ( this.hideOnChoose
) {
6931 this.toggle( false );
6939 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6941 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6943 // Reevaluate clipping
6952 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6954 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6956 // Reevaluate clipping
6965 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6967 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6969 // Reevaluate clipping
6976 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
6977 * `.toggle( true )` after its #$element is attached to the DOM.
6979 * Do not show the menu while it is not attached to the DOM. The calculations required to display
6980 * it in the right place and with the right dimensions only work correctly while it is attached.
6981 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
6982 * strictly enforced, so currently it only generates a warning in the browser console.
6986 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6989 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6990 change
= visible
!== this.isVisible();
6992 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
6993 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
6994 this.warnedUnattached
= true;
6998 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7002 this.bindKeyDownListener();
7003 this.bindKeyPressListener();
7005 this.toggleClipping( true );
7007 if ( this.getSelectedItem() ) {
7008 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7012 if ( this.autoHide
) {
7013 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7016 this.unbindKeyDownListener();
7017 this.unbindKeyPressListener();
7018 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7019 this.toggleClipping( false );
7027 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7028 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7029 * users can interact with it.
7031 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7032 * OO.ui.DropdownInputWidget instead.
7035 * // Example: A DropdownWidget with a menu that contains three options
7036 * var dropDown = new OO.ui.DropdownWidget( {
7037 * label: 'Dropdown menu: Select a menu option',
7040 * new OO.ui.MenuOptionWidget( {
7044 * new OO.ui.MenuOptionWidget( {
7048 * new OO.ui.MenuOptionWidget( {
7056 * $( 'body' ).append( dropDown.$element );
7058 * dropDown.getMenu().selectItemByData( 'b' );
7060 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7062 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7064 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7067 * @extends OO.ui.Widget
7068 * @mixins OO.ui.mixin.IconElement
7069 * @mixins OO.ui.mixin.IndicatorElement
7070 * @mixins OO.ui.mixin.LabelElement
7071 * @mixins OO.ui.mixin.TitledElement
7072 * @mixins OO.ui.mixin.TabIndexedElement
7075 * @param {Object} [config] Configuration options
7076 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
7077 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7078 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7079 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7081 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7082 // Configuration initialization
7083 config
= $.extend( { indicator
: 'down' }, config
);
7085 // Parent constructor
7086 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7088 // Properties (must be set before TabIndexedElement constructor call)
7089 this.$handle
= this.$( '<span>' );
7090 this.$overlay
= config
.$overlay
|| this.$element
;
7092 // Mixin constructors
7093 OO
.ui
.mixin
.IconElement
.call( this, config
);
7094 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7095 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7096 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7097 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7100 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
7102 $container
: this.$element
7107 click
: this.onClick
.bind( this ),
7108 keydown
: this.onKeyDown
.bind( this ),
7109 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7110 keypress
: this.menu
.onKeyPressHandler
,
7111 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7113 this.menu
.connect( this, {
7114 select
: 'onMenuSelect',
7115 toggle
: 'onMenuToggle'
7120 .addClass( 'oo-ui-dropdownWidget-handle' )
7121 .append( this.$icon
, this.$label
, this.$indicator
);
7123 .addClass( 'oo-ui-dropdownWidget' )
7124 .append( this.$handle
);
7125 this.$overlay
.append( this.menu
.$element
);
7130 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7131 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7132 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7133 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7134 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7135 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7142 * @return {OO.ui.MenuSelectWidget} Menu of widget
7144 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7149 * Handles menu select events.
7152 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7154 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7158 this.setLabel( null );
7162 selectedLabel
= item
.getLabel();
7164 // If the label is a DOM element, clone it, because setLabel will append() it
7165 if ( selectedLabel
instanceof jQuery
) {
7166 selectedLabel
= selectedLabel
.clone();
7169 this.setLabel( selectedLabel
);
7173 * Handle menu toggle events.
7176 * @param {boolean} isVisible Menu toggle event
7178 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7179 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7183 * Handle mouse click events.
7186 * @param {jQuery.Event} e Mouse click event
7188 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7189 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7196 * Handle key down events.
7199 * @param {jQuery.Event} e Key down event
7201 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7203 !this.isDisabled() &&
7205 e
.which
=== OO
.ui
.Keys
.ENTER
||
7207 !this.menu
.isVisible() &&
7209 e
.which
=== OO
.ui
.Keys
.SPACE
||
7210 e
.which
=== OO
.ui
.Keys
.UP
||
7211 e
.which
=== OO
.ui
.Keys
.DOWN
7222 * RadioOptionWidget is an option widget that looks like a radio button.
7223 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7224 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7226 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7229 * @extends OO.ui.OptionWidget
7232 * @param {Object} [config] Configuration options
7234 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7235 // Configuration initialization
7236 config
= config
|| {};
7238 // Properties (must be done before parent constructor which calls #setDisabled)
7239 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7241 // Parent constructor
7242 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7245 // Remove implicit role, we're handling it ourselves
7246 this.radio
.$input
.attr( 'role', 'presentation' );
7248 .addClass( 'oo-ui-radioOptionWidget' )
7249 .attr( 'role', 'radio' )
7250 .attr( 'aria-checked', 'false' )
7251 .removeAttr( 'aria-selected' )
7252 .prepend( this.radio
.$element
);
7257 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7259 /* Static Properties */
7265 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7271 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7277 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7283 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7290 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7291 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7293 this.radio
.setSelected( state
);
7295 .attr( 'aria-checked', state
.toString() )
7296 .removeAttr( 'aria-selected' );
7304 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7305 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7307 this.radio
.setDisabled( this.isDisabled() );
7313 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7314 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7315 * an interface for adding, removing and selecting options.
7316 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7318 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7319 * OO.ui.RadioSelectInputWidget instead.
7322 * // A RadioSelectWidget with RadioOptions.
7323 * var option1 = new OO.ui.RadioOptionWidget( {
7325 * label: 'Selected radio option'
7328 * var option2 = new OO.ui.RadioOptionWidget( {
7330 * label: 'Unselected radio option'
7333 * var radioSelect=new OO.ui.RadioSelectWidget( {
7334 * items: [ option1, option2 ]
7337 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7338 * radioSelect.selectItem( option1 );
7340 * $( 'body' ).append( radioSelect.$element );
7342 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7346 * @extends OO.ui.SelectWidget
7347 * @mixins OO.ui.mixin.TabIndexedElement
7350 * @param {Object} [config] Configuration options
7352 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7353 // Parent constructor
7354 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7356 // Mixin constructors
7357 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7361 focus
: this.bindKeyDownListener
.bind( this ),
7362 blur
: this.unbindKeyDownListener
.bind( this )
7367 .addClass( 'oo-ui-radioSelectWidget' )
7368 .attr( 'role', 'radiogroup' );
7373 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7374 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7377 * MultioptionWidgets are special elements that can be selected and configured with data. The
7378 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7379 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7380 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7382 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7385 * @extends OO.ui.Widget
7386 * @mixins OO.ui.mixin.ItemWidget
7387 * @mixins OO.ui.mixin.LabelElement
7390 * @param {Object} [config] Configuration options
7391 * @cfg {boolean} [selected=false] Whether the option is initially selected
7393 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7394 // Configuration initialization
7395 config
= config
|| {};
7397 // Parent constructor
7398 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7400 // Mixin constructors
7401 OO
.ui
.mixin
.ItemWidget
.call( this );
7402 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7405 this.selected
= null;
7409 .addClass( 'oo-ui-multioptionWidget' )
7410 .append( this.$label
);
7411 this.setSelected( config
.selected
);
7416 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7417 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7418 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7425 * A change event is emitted when the selected state of the option changes.
7427 * @param {boolean} selected Whether the option is now selected
7433 * Check if the option is selected.
7435 * @return {boolean} Item is selected
7437 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7438 return this.selected
;
7442 * Set the option’s selected state. In general, all modifications to the selection
7443 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7444 * method instead of this method.
7446 * @param {boolean} [state=false] Select option
7449 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7451 if ( this.selected
!== state
) {
7452 this.selected
= state
;
7453 this.emit( 'change', state
);
7454 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7460 * MultiselectWidget allows selecting multiple options from a list.
7462 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7464 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7468 * @extends OO.ui.Widget
7469 * @mixins OO.ui.mixin.GroupWidget
7472 * @param {Object} [config] Configuration options
7473 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7475 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7476 // Parent constructor
7477 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7479 // Configuration initialization
7480 config
= config
|| {};
7482 // Mixin constructors
7483 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7486 this.aggregate( { change
: 'select' } );
7487 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7488 // by GroupElement only when items are added/removed
7489 this.connect( this, { select
: [ 'emit', 'change' ] } );
7492 if ( config
.items
) {
7493 this.addItems( config
.items
);
7495 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7496 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7497 .append( this.$group
);
7502 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7503 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7510 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7516 * A select event is emitted when an item is selected or deselected.
7522 * Get options that are selected.
7524 * @return {OO.ui.MultioptionWidget[]} Selected options
7526 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7527 return this.items
.filter( function ( item
) {
7528 return item
.isSelected();
7533 * Get the data of options that are selected.
7535 * @return {Object[]|string[]} Values of selected options
7537 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7538 return this.getSelectedItems().map( function ( item
) {
7544 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7546 * @param {OO.ui.MultioptionWidget[]} items Items to select
7549 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7550 this.items
.forEach( function ( item
) {
7551 var selected
= items
.indexOf( item
) !== -1;
7552 item
.setSelected( selected
);
7558 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7560 * @param {Object[]|string[]} datas Values of items to select
7563 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7566 items
= datas
.map( function ( data
) {
7567 return widget
.getItemFromData( data
);
7569 this.selectItems( items
);
7574 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7575 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7576 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7578 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7581 * @extends OO.ui.MultioptionWidget
7584 * @param {Object} [config] Configuration options
7586 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7587 // Configuration initialization
7588 config
= config
|| {};
7590 // Properties (must be done before parent constructor which calls #setDisabled)
7591 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7593 // Parent constructor
7594 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7597 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7598 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7602 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7603 .prepend( this.checkbox
.$element
);
7608 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7610 /* Static Properties */
7616 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7621 * Handle checkbox selected state change.
7625 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7626 this.setSelected( this.checkbox
.isSelected() );
7632 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7633 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7634 this.checkbox
.setSelected( state
);
7641 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7642 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7643 this.checkbox
.setDisabled( this.isDisabled() );
7650 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7651 this.checkbox
.focus();
7655 * Handle key down events.
7658 * @param {jQuery.Event} e
7660 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7662 element
= this.getElementGroup(),
7665 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7666 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7667 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7668 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7678 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7679 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7680 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7681 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7683 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7684 * OO.ui.CheckboxMultiselectInputWidget instead.
7687 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7688 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7691 * label: 'Selected checkbox'
7694 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7696 * label: 'Unselected checkbox'
7699 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7700 * items: [ option1, option2 ]
7703 * $( 'body' ).append( multiselect.$element );
7705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7708 * @extends OO.ui.MultiselectWidget
7711 * @param {Object} [config] Configuration options
7713 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7714 // Parent constructor
7715 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7718 this.$lastClicked
= null;
7721 this.$group
.on( 'click', this.onClick
.bind( this ) );
7725 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7730 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7735 * Get an option by its position relative to the specified item (or to the start of the option array,
7736 * if item is `null`). The direction in which to search through the option array is specified with a
7737 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7738 * `null` if there are no options in the array.
7740 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7741 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7742 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7744 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7745 var currentIndex
, nextIndex
, i
,
7746 increase
= direction
> 0 ? 1 : -1,
7747 len
= this.items
.length
;
7750 currentIndex
= this.items
.indexOf( item
);
7751 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7753 // If no item is selected and moving forward, start at the beginning.
7754 // If moving backward, start at the end.
7755 nextIndex
= direction
> 0 ? 0 : len
- 1;
7758 for ( i
= 0; i
< len
; i
++ ) {
7759 item
= this.items
[ nextIndex
];
7760 if ( item
&& !item
.isDisabled() ) {
7763 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7769 * Handle click events on checkboxes.
7771 * @param {jQuery.Event} e
7773 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7774 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7775 $lastClicked
= this.$lastClicked
,
7776 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7777 .not( '.oo-ui-widget-disabled' );
7779 // Allow selecting multiple options at once by Shift-clicking them
7780 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7781 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7782 lastClickedIndex
= $options
.index( $lastClicked
);
7783 nowClickedIndex
= $options
.index( $nowClicked
);
7784 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7785 // browser. In either case we don't need custom handling.
7786 if ( nowClickedIndex
!== lastClickedIndex
) {
7788 wasSelected
= items
[ nowClickedIndex
].isSelected();
7789 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7791 // This depends on the DOM order of the items and the order of the .items array being the same.
7792 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7793 if ( !items
[ i
].isDisabled() ) {
7794 items
[ i
].setSelected( !wasSelected
);
7797 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7798 // handling first, then set our value. The order in which events happen is different for
7799 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7800 // non-click actions that change the checkboxes.
7802 setTimeout( function () {
7803 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7804 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7810 if ( $nowClicked
.length
) {
7811 this.$lastClicked
= $nowClicked
;
7816 * FloatingMenuSelectWidget is a menu that will stick under a specified
7817 * container, even when it is inserted elsewhere in the document (for example,
7818 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7819 * menu from being clipped too aggresively.
7821 * The menu's position is automatically calculated and maintained when the menu
7822 * is toggled or the window is resized.
7824 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7827 * @extends OO.ui.MenuSelectWidget
7828 * @mixins OO.ui.mixin.FloatableElement
7831 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7832 * Deprecated, omit this parameter and specify `$container` instead.
7833 * @param {Object} [config] Configuration options
7834 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7836 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7837 // Allow 'inputWidget' parameter and config for backwards compatibility
7838 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7839 config
= inputWidget
;
7840 inputWidget
= config
.inputWidget
;
7843 // Configuration initialization
7844 config
= config
|| {};
7846 // Parent constructor
7847 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7849 // Properties (must be set before mixin constructors)
7850 this.inputWidget
= inputWidget
; // For backwards compatibility
7851 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7853 // Mixins constructors
7854 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7857 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7858 // For backwards compatibility
7859 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7864 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7865 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7872 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7874 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7875 change
= visible
!== this.isVisible();
7877 if ( change
&& visible
) {
7878 // Make sure the width is set before the parent method runs.
7879 this.setIdealSize( this.$container
.width() );
7883 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7884 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7887 this.togglePositioning( this.isVisible() );
7894 * Progress bars visually display the status of an operation, such as a download,
7895 * and can be either determinate or indeterminate:
7897 * - **determinate** process bars show the percent of an operation that is complete.
7899 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7900 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7901 * not use percentages.
7903 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7906 * // Examples of determinate and indeterminate progress bars.
7907 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7910 * var progressBar2 = new OO.ui.ProgressBarWidget();
7912 * // Create a FieldsetLayout to layout progress bars
7913 * var fieldset = new OO.ui.FieldsetLayout;
7914 * fieldset.addItems( [
7915 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7916 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7918 * $( 'body' ).append( fieldset.$element );
7921 * @extends OO.ui.Widget
7924 * @param {Object} [config] Configuration options
7925 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7926 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7927 * By default, the progress bar is indeterminate.
7929 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7930 // Configuration initialization
7931 config
= config
|| {};
7933 // Parent constructor
7934 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7937 this.$bar
= $( '<div>' );
7938 this.progress
= null;
7941 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7942 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7945 role
: 'progressbar',
7947 'aria-valuemax': 100
7949 .addClass( 'oo-ui-progressBarWidget' )
7950 .append( this.$bar
);
7955 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
7957 /* Static Properties */
7963 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
7968 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7970 * @return {number|boolean} Progress percent
7972 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
7973 return this.progress
;
7977 * Set the percent of the process completed or `false` for an indeterminate process.
7979 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7981 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
7982 this.progress
= progress
;
7984 if ( progress
!== false ) {
7985 this.$bar
.css( 'width', this.progress
+ '%' );
7986 this.$element
.attr( 'aria-valuenow', this.progress
);
7988 this.$bar
.css( 'width', '' );
7989 this.$element
.removeAttr( 'aria-valuenow' );
7991 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
7995 * InputWidget is the base class for all input widgets, which
7996 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7997 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7998 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8000 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8004 * @extends OO.ui.Widget
8005 * @mixins OO.ui.mixin.FlaggedElement
8006 * @mixins OO.ui.mixin.TabIndexedElement
8007 * @mixins OO.ui.mixin.TitledElement
8008 * @mixins OO.ui.mixin.AccessKeyedElement
8011 * @param {Object} [config] Configuration options
8012 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8013 * @cfg {string} [value=''] The value of the input.
8014 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8015 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8016 * before it is accepted.
8018 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8019 // Configuration initialization
8020 config
= config
|| {};
8022 // Parent constructor
8023 OO
.ui
.InputWidget
.parent
.call( this, config
);
8026 // See #reusePreInfuseDOM about config.$input
8027 this.$input
= config
.$input
|| this.getInputElement( config
);
8029 this.inputFilter
= config
.inputFilter
;
8031 // Mixin constructors
8032 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8033 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8034 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8035 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8038 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8042 .addClass( 'oo-ui-inputWidget-input' )
8043 .attr( 'name', config
.name
)
8044 .prop( 'disabled', this.isDisabled() );
8046 .addClass( 'oo-ui-inputWidget' )
8047 .append( this.$input
);
8048 this.setValue( config
.value
);
8050 this.setDir( config
.dir
);
8056 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8057 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8058 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8059 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8060 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8062 /* Static Properties */
8068 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
8070 /* Static Methods */
8075 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8076 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8077 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8078 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8085 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8086 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8087 if ( config
.$input
&& config
.$input
.length
) {
8088 state
.value
= config
.$input
.val();
8089 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8090 state
.focus
= config
.$input
.is( ':focus' );
8100 * A change event is emitted when the value of the input changes.
8102 * @param {string} value
8108 * Get input element.
8110 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8111 * different circumstances. The element must have a `value` property (like form elements).
8114 * @param {Object} config Configuration options
8115 * @return {jQuery} Input element
8117 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8118 return $( '<input>' );
8122 * Get input element's ID.
8124 * If the element already has an ID then that is returned, otherwise unique ID is
8125 * generated, set on the element, and returned.
8127 * @return {string} The ID of the element
8129 OO
.ui
.InputWidget
.prototype.getInputId = function () {
8130 var id
= this.$input
.attr( 'id' );
8132 if ( id
=== undefined ) {
8133 id
= OO
.ui
.generateElementId();
8134 this.$input
.attr( 'id', id
);
8141 * Handle potentially value-changing events.
8144 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8146 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8148 if ( !this.isDisabled() ) {
8149 // Allow the stack to clear so the value will be updated
8150 setTimeout( function () {
8151 widget
.setValue( widget
.$input
.val() );
8157 * Get the value of the input.
8159 * @return {string} Input value
8161 OO
.ui
.InputWidget
.prototype.getValue = function () {
8162 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8163 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8164 var value
= this.$input
.val();
8165 if ( this.value
!== value
) {
8166 this.setValue( value
);
8172 * Set the directionality of the input.
8174 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8177 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8178 this.$input
.prop( 'dir', dir
);
8183 * Set the value of the input.
8185 * @param {string} value New value
8189 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8190 value
= this.cleanUpValue( value
);
8191 // Update the DOM if it has changed. Note that with cleanUpValue, it
8192 // is possible for the DOM value to change without this.value changing.
8193 if ( this.$input
.val() !== value
) {
8194 this.$input
.val( value
);
8196 if ( this.value
!== value
) {
8198 this.emit( 'change', this.value
);
8204 * Clean up incoming value.
8206 * Ensures value is a string, and converts undefined and null to empty string.
8209 * @param {string} value Original value
8210 * @return {string} Cleaned up value
8212 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8213 if ( value
=== undefined || value
=== null ) {
8215 } else if ( this.inputFilter
) {
8216 return this.inputFilter( String( value
) );
8218 return String( value
);
8223 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8224 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8227 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8228 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8229 if ( !this.isDisabled() ) {
8230 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8231 this.$input
.click();
8233 if ( this.$input
.is( ':input' ) ) {
8234 this.$input
[ 0 ].focus();
8242 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8243 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8244 if ( this.$input
) {
8245 this.$input
.prop( 'disabled', this.isDisabled() );
8255 OO
.ui
.InputWidget
.prototype.focus = function () {
8256 this.$input
[ 0 ].focus();
8265 OO
.ui
.InputWidget
.prototype.blur = function () {
8266 this.$input
[ 0 ].blur();
8273 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8274 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8275 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8276 this.setValue( state
.value
);
8278 if ( state
.focus
) {
8284 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8285 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8286 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8287 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8288 * [OOjs UI documentation on MediaWiki] [1] for more information.
8291 * // A ButtonInputWidget rendered as an HTML button, the default.
8292 * var button = new OO.ui.ButtonInputWidget( {
8293 * label: 'Input button',
8297 * $( 'body' ).append( button.$element );
8299 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8302 * @extends OO.ui.InputWidget
8303 * @mixins OO.ui.mixin.ButtonElement
8304 * @mixins OO.ui.mixin.IconElement
8305 * @mixins OO.ui.mixin.IndicatorElement
8306 * @mixins OO.ui.mixin.LabelElement
8307 * @mixins OO.ui.mixin.TitledElement
8310 * @param {Object} [config] Configuration options
8311 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8312 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8313 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8314 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8315 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8317 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8318 // Configuration initialization
8319 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8321 // See InputWidget#reusePreInfuseDOM about config.$input
8322 if ( config
.$input
) {
8323 config
.$input
.empty();
8326 // Properties (must be set before parent constructor, which calls #setValue)
8327 this.useInputTag
= config
.useInputTag
;
8329 // Parent constructor
8330 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8332 // Mixin constructors
8333 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8334 OO
.ui
.mixin
.IconElement
.call( this, config
);
8335 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8336 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8337 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8340 if ( !config
.useInputTag
) {
8341 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8343 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8348 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8349 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8350 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8351 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8352 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8353 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8355 /* Static Properties */
8358 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
8359 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
8364 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
8370 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8378 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8380 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8381 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8387 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8389 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8390 * text, or `null` for no label
8393 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8394 if ( typeof label
=== 'function' ) {
8395 label
= OO
.ui
.resolveMsg( label
);
8398 if ( this.useInputTag
) {
8399 // Discard non-plaintext labels
8400 if ( typeof label
!== 'string' ) {
8404 this.$input
.val( label
);
8407 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8411 * Set the value of the input.
8413 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8414 * they do not support {@link #value values}.
8416 * @param {string} value New value
8419 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8420 if ( !this.useInputTag
) {
8421 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8427 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8428 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8429 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8430 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8432 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8435 * // An example of selected, unselected, and disabled checkbox inputs
8436 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8440 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8443 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8447 * // Create a fieldset layout with fields for each checkbox.
8448 * var fieldset = new OO.ui.FieldsetLayout( {
8449 * label: 'Checkboxes'
8451 * fieldset.addItems( [
8452 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8453 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8454 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8456 * $( 'body' ).append( fieldset.$element );
8458 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8461 * @extends OO.ui.InputWidget
8464 * @param {Object} [config] Configuration options
8465 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8467 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8468 // Configuration initialization
8469 config
= config
|| {};
8471 // Parent constructor
8472 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8476 .addClass( 'oo-ui-checkboxInputWidget' )
8477 // Required for pretty styling in MediaWiki theme
8478 .append( $( '<span>' ) );
8479 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8484 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8486 /* Static Properties */
8492 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8494 /* Static Methods */
8499 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8500 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8501 state
.checked
= config
.$input
.prop( 'checked' );
8511 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8512 return $( '<input>' ).attr( 'type', 'checkbox' );
8518 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8520 if ( !this.isDisabled() ) {
8521 // Allow the stack to clear so the value will be updated
8522 setTimeout( function () {
8523 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8529 * Set selection state of this checkbox.
8531 * @param {boolean} state `true` for selected
8534 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8536 if ( this.selected
!== state
) {
8537 this.selected
= state
;
8538 this.$input
.prop( 'checked', this.selected
);
8539 this.emit( 'change', this.selected
);
8545 * Check if this checkbox is selected.
8547 * @return {boolean} Checkbox is selected
8549 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8550 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8551 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8552 var selected
= this.$input
.prop( 'checked' );
8553 if ( this.selected
!== selected
) {
8554 this.setSelected( selected
);
8556 return this.selected
;
8562 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8563 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8564 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8565 this.setSelected( state
.checked
);
8570 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8571 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8572 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8573 * more information about input widgets.
8575 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8576 * are no options. If no `value` configuration option is provided, the first option is selected.
8577 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8579 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8582 * // Example: A DropdownInputWidget with three options
8583 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8585 * { data: 'a', label: 'First' },
8586 * { data: 'b', label: 'Second'},
8587 * { data: 'c', label: 'Third' }
8590 * $( 'body' ).append( dropdownInput.$element );
8592 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8595 * @extends OO.ui.InputWidget
8596 * @mixins OO.ui.mixin.TitledElement
8599 * @param {Object} [config] Configuration options
8600 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8601 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8603 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8604 // Configuration initialization
8605 config
= config
|| {};
8607 // See InputWidget#reusePreInfuseDOM about config.$input
8608 if ( config
.$input
) {
8609 config
.$input
.addClass( 'oo-ui-element-hidden' );
8612 // Properties (must be done before parent constructor which calls #setDisabled)
8613 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8615 // Parent constructor
8616 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8618 // Mixin constructors
8619 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8622 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8625 this.setOptions( config
.options
|| [] );
8627 .addClass( 'oo-ui-dropdownInputWidget' )
8628 .append( this.dropdownWidget
.$element
);
8633 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8634 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8642 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8643 return $( '<input>' ).attr( 'type', 'hidden' );
8647 * Handles menu select events.
8650 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8652 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8653 this.setValue( item
.getData() );
8659 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8660 value
= this.cleanUpValue( value
);
8661 this.dropdownWidget
.getMenu().selectItemByData( value
);
8662 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8669 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8670 this.dropdownWidget
.setDisabled( state
);
8671 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8676 * Set the options available for this input.
8678 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8681 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8683 value
= this.getValue(),
8686 // Rebuild the dropdown menu
8687 this.dropdownWidget
.getMenu()
8689 .addItems( options
.map( function ( opt
) {
8690 var optValue
= widget
.cleanUpValue( opt
.data
);
8692 if ( opt
.optgroup
=== undefined ) {
8693 return new OO
.ui
.MenuOptionWidget( {
8695 label
: opt
.label
!== undefined ? opt
.label
: optValue
8698 return new OO
.ui
.MenuSectionOptionWidget( {
8704 // Restore the previous value, or reset to something sensible
8705 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8706 // Previous value is still available, ensure consistency with the dropdown
8707 this.setValue( value
);
8709 // No longer valid, reset
8710 if ( options
.length
) {
8711 this.setValue( options
[ 0 ].data
);
8721 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8722 this.dropdownWidget
.getMenu().toggle( true );
8729 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8730 this.dropdownWidget
.getMenu().toggle( false );
8735 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8736 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8737 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8738 * please see the [OOjs UI documentation on MediaWiki][1].
8740 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8743 * // An example of selected, unselected, and disabled radio inputs
8744 * var radio1 = new OO.ui.RadioInputWidget( {
8748 * var radio2 = new OO.ui.RadioInputWidget( {
8751 * var radio3 = new OO.ui.RadioInputWidget( {
8755 * // Create a fieldset layout with fields for each radio button.
8756 * var fieldset = new OO.ui.FieldsetLayout( {
8757 * label: 'Radio inputs'
8759 * fieldset.addItems( [
8760 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8761 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8762 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8764 * $( 'body' ).append( fieldset.$element );
8766 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8769 * @extends OO.ui.InputWidget
8772 * @param {Object} [config] Configuration options
8773 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8775 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8776 // Configuration initialization
8777 config
= config
|| {};
8779 // Parent constructor
8780 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8784 .addClass( 'oo-ui-radioInputWidget' )
8785 // Required for pretty styling in MediaWiki theme
8786 .append( $( '<span>' ) );
8787 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8792 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8794 /* Static Properties */
8800 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
8802 /* Static Methods */
8807 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8808 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8809 state
.checked
= config
.$input
.prop( 'checked' );
8819 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8820 return $( '<input>' ).attr( 'type', 'radio' );
8826 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8827 // RadioInputWidget doesn't track its state.
8831 * Set selection state of this radio button.
8833 * @param {boolean} state `true` for selected
8836 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8837 // RadioInputWidget doesn't track its state.
8838 this.$input
.prop( 'checked', state
);
8843 * Check if this radio button is selected.
8845 * @return {boolean} Radio is selected
8847 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8848 return this.$input
.prop( 'checked' );
8854 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8855 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8856 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8857 this.setSelected( state
.checked
);
8862 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8863 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8864 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8865 * more information about input widgets.
8867 * This and OO.ui.DropdownInputWidget support the same configuration options.
8870 * // Example: A RadioSelectInputWidget with three options
8871 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8873 * { data: 'a', label: 'First' },
8874 * { data: 'b', label: 'Second'},
8875 * { data: 'c', label: 'Third' }
8878 * $( 'body' ).append( radioSelectInput.$element );
8880 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8883 * @extends OO.ui.InputWidget
8886 * @param {Object} [config] Configuration options
8887 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8889 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8890 // Configuration initialization
8891 config
= config
|| {};
8893 // Properties (must be done before parent constructor which calls #setDisabled)
8894 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8896 // Parent constructor
8897 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8900 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8903 this.setOptions( config
.options
|| [] );
8905 .addClass( 'oo-ui-radioSelectInputWidget' )
8906 .append( this.radioSelectWidget
.$element
);
8911 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8913 /* Static Properties */
8919 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8921 /* Static Methods */
8926 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8927 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8928 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8935 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8936 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8937 // Cannot reuse the `<input type=radio>` set
8938 delete config
.$input
;
8948 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8949 return $( '<input>' ).attr( 'type', 'hidden' );
8953 * Handles menu select events.
8956 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8958 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
8959 this.setValue( item
.getData() );
8965 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
8966 value
= this.cleanUpValue( value
);
8967 this.radioSelectWidget
.selectItemByData( value
);
8968 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8975 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
8976 this.radioSelectWidget
.setDisabled( state
);
8977 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8982 * Set the options available for this input.
8984 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8987 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
8989 value
= this.getValue(),
8992 // Rebuild the radioSelect menu
8993 this.radioSelectWidget
8995 .addItems( options
.map( function ( opt
) {
8996 var optValue
= widget
.cleanUpValue( opt
.data
);
8997 return new OO
.ui
.RadioOptionWidget( {
8999 label
: opt
.label
!== undefined ? opt
.label
: optValue
9003 // Restore the previous value, or reset to something sensible
9004 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9005 // Previous value is still available, ensure consistency with the radioSelect
9006 this.setValue( value
);
9008 // No longer valid, reset
9009 if ( options
.length
) {
9010 this.setValue( options
[ 0 ].data
);
9018 * CheckboxMultiselectInputWidget is a
9019 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9020 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9021 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9022 * more information about input widgets.
9025 * // Example: A CheckboxMultiselectInputWidget with three options
9026 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9028 * { data: 'a', label: 'First' },
9029 * { data: 'b', label: 'Second'},
9030 * { data: 'c', label: 'Third' }
9033 * $( 'body' ).append( multiselectInput.$element );
9035 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9038 * @extends OO.ui.InputWidget
9041 * @param {Object} [config] Configuration options
9042 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9044 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9045 // Configuration initialization
9046 config
= config
|| {};
9048 // Properties (must be done before parent constructor which calls #setDisabled)
9049 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9051 // Parent constructor
9052 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9055 this.inputName
= config
.name
;
9059 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9060 .append( this.checkboxMultiselectWidget
.$element
);
9061 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9062 this.$input
.detach();
9063 this.setOptions( config
.options
|| [] );
9064 // Have to repeat this from parent, as we need options to be set up for this to make sense
9065 this.setValue( config
.value
);
9070 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9072 /* Static Properties */
9078 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
9080 /* Static Methods */
9085 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9086 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9087 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9088 .toArray().map( function ( el
) { return el
.value
; } );
9095 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9096 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9097 // Cannot reuse the `<input type=checkbox>` set
9098 delete config
.$input
;
9108 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9110 return $( '<div>' );
9116 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9117 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9118 .toArray().map( function ( el
) { return el
.value
; } );
9119 if ( this.value
!== value
) {
9120 this.setValue( value
);
9128 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9129 value
= this.cleanUpValue( value
);
9130 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9131 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9136 * Clean up incoming value.
9138 * @param {string[]} value Original value
9139 * @return {string[]} Cleaned up value
9141 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9144 if ( !Array
.isArray( value
) ) {
9147 for ( i
= 0; i
< value
.length
; i
++ ) {
9149 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9150 // Remove options that we don't have here
9151 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9154 cleanValue
.push( singleValue
);
9162 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9163 this.checkboxMultiselectWidget
.setDisabled( state
);
9164 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9169 * Set the options available for this input.
9171 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9174 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9177 // Rebuild the checkboxMultiselectWidget menu
9178 this.checkboxMultiselectWidget
9180 .addItems( options
.map( function ( opt
) {
9181 var optValue
, item
, optDisabled
;
9183 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9184 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9185 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9187 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9188 disabled
: optDisabled
9190 // Set the 'name' and 'value' for form submission
9191 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9192 item
.checkbox
.setValue( optValue
);
9196 // Re-set the value, checking the checkboxes as needed.
9197 // This will also get rid of any stale options that we just removed.
9198 this.setValue( this.getValue() );
9204 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9205 * size of the field as well as its presentation. In addition, these widgets can be configured
9206 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9207 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9208 * which modifies incoming values rather than validating them.
9209 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9211 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9214 * // Example of a text input widget
9215 * var textInput = new OO.ui.TextInputWidget( {
9216 * value: 'Text input'
9218 * $( 'body' ).append( textInput.$element );
9220 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9223 * @extends OO.ui.InputWidget
9224 * @mixins OO.ui.mixin.IconElement
9225 * @mixins OO.ui.mixin.IndicatorElement
9226 * @mixins OO.ui.mixin.PendingElement
9227 * @mixins OO.ui.mixin.LabelElement
9230 * @param {Object} [config] Configuration options
9231 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9232 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9234 * Some values of `type` result in additional behaviors:
9236 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9237 * empties the text field
9238 * @cfg {string} [placeholder] Placeholder text
9239 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9240 * instruct the browser to focus this widget.
9241 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9242 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9243 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9244 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9245 * specifies minimum number of rows to display.
9246 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9247 * Use the #maxRows config to specify a maximum number of displayed rows.
9248 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9249 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9250 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9251 * the value or placeholder text: `'before'` or `'after'`
9252 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9253 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9254 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9255 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9256 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9257 * value for it to be considered valid; when Function, a function receiving the value as parameter
9258 * that must return true, or promise resolving to true, for it to be considered valid.
9260 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9261 // Configuration initialization
9262 config
= $.extend( {
9264 labelPosition
: 'after'
9267 if ( config
.type
=== 'search' ) {
9268 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9269 if ( config
.icon
=== undefined ) {
9270 config
.icon
= 'search';
9272 // indicator: 'clear' is set dynamically later, depending on value
9275 // Parent constructor
9276 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9278 // Mixin constructors
9279 OO
.ui
.mixin
.IconElement
.call( this, config
);
9280 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9281 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9282 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9285 this.type
= this.getSaneType( config
);
9286 this.readOnly
= false;
9287 this.required
= false;
9288 this.multiline
= !!config
.multiline
;
9289 this.autosize
= !!config
.autosize
;
9290 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9291 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9292 this.validate
= null;
9293 this.styleHeight
= null;
9294 this.scrollWidth
= null;
9296 // Clone for resizing
9297 if ( this.autosize
) {
9298 this.$clone
= this.$input
9300 .insertAfter( this.$input
)
9301 .attr( 'aria-hidden', 'true' )
9302 .addClass( 'oo-ui-element-hidden' );
9305 this.setValidation( config
.validate
);
9306 this.setLabelPosition( config
.labelPosition
);
9310 keypress
: this.onKeyPress
.bind( this ),
9311 blur
: this.onBlur
.bind( this ),
9312 focus
: this.onFocus
.bind( this )
9314 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9315 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9316 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9317 this.connect( this, {
9319 disable
: 'onDisable'
9321 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9325 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9326 .append( this.$icon
, this.$indicator
);
9327 this.setReadOnly( !!config
.readOnly
);
9328 this.setRequired( !!config
.required
);
9329 this.updateSearchIndicator();
9330 if ( config
.placeholder
!== undefined ) {
9331 this.$input
.attr( 'placeholder', config
.placeholder
);
9333 if ( config
.maxLength
!== undefined ) {
9334 this.$input
.attr( 'maxlength', config
.maxLength
);
9336 if ( config
.autofocus
) {
9337 this.$input
.attr( 'autofocus', 'autofocus' );
9339 if ( config
.autocomplete
=== false ) {
9340 this.$input
.attr( 'autocomplete', 'off' );
9341 // Turning off autocompletion also disables "form caching" when the user navigates to a
9342 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9344 beforeunload: function () {
9345 this.$input
.removeAttr( 'autocomplete' );
9347 pageshow: function () {
9348 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9349 // whole page... it shouldn't hurt, though.
9350 this.$input
.attr( 'autocomplete', 'off' );
9354 if ( this.multiline
&& config
.rows
) {
9355 this.$input
.attr( 'rows', config
.rows
);
9357 if ( this.label
|| config
.autosize
) {
9358 this.isWaitingToBeAttached
= true;
9359 this.installParentChangeDetector();
9365 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9366 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9367 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9368 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9369 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9371 /* Static Properties */
9373 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9378 /* Static Methods */
9383 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9384 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9385 if ( config
.multiline
) {
9386 state
.scrollTop
= config
.$input
.scrollTop();
9394 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9396 * Not emitted if the input is multiline.
9402 * A `resize` event is emitted when autosize is set and the widget resizes
9410 * Handle icon mouse down events.
9413 * @param {jQuery.Event} e Mouse down event
9415 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9416 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9417 this.$input
[ 0 ].focus();
9423 * Handle indicator mouse down events.
9426 * @param {jQuery.Event} e Mouse down event
9428 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9429 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9430 if ( this.type
=== 'search' ) {
9431 // Clear the text field
9432 this.setValue( '' );
9434 this.$input
[ 0 ].focus();
9440 * Handle key press events.
9443 * @param {jQuery.Event} e Key press event
9444 * @fires enter If enter key is pressed and input is not multiline
9446 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9447 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9448 this.emit( 'enter', e
);
9453 * Handle blur events.
9456 * @param {jQuery.Event} e Blur event
9458 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9459 this.setValidityFlag();
9463 * Handle focus events.
9466 * @param {jQuery.Event} e Focus event
9468 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9469 if ( this.isWaitingToBeAttached
) {
9470 // If we've received focus, then we must be attached to the document, and if
9471 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9472 this.onElementAttach();
9474 this.setValidityFlag( true );
9478 * Handle element attach events.
9481 * @param {jQuery.Event} e Element attach event
9483 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9484 this.isWaitingToBeAttached
= false;
9485 // Any previously calculated size is now probably invalid if we reattached elsewhere
9486 this.valCache
= null;
9488 this.positionLabel();
9492 * Handle change events.
9494 * @param {string} value
9497 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9498 this.updateSearchIndicator();
9503 * Handle debounced change events.
9505 * @param {string} value
9508 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9509 this.setValidityFlag();
9513 * Handle disable events.
9515 * @param {boolean} disabled Element is disabled
9518 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9519 this.updateSearchIndicator();
9523 * Check if the input is {@link #readOnly read-only}.
9527 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9528 return this.readOnly
;
9532 * Set the {@link #readOnly read-only} state of the input.
9534 * @param {boolean} state Make input read-only
9537 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9538 this.readOnly
= !!state
;
9539 this.$input
.prop( 'readOnly', this.readOnly
);
9540 this.updateSearchIndicator();
9545 * Check if the input is {@link #required required}.
9549 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9550 return this.required
;
9554 * Set the {@link #required required} state of the input.
9556 * @param {boolean} state Make input required
9559 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9560 this.required
= !!state
;
9561 if ( this.required
) {
9563 .attr( 'required', 'required' )
9564 .attr( 'aria-required', 'true' );
9565 if ( this.getIndicator() === null ) {
9566 this.setIndicator( 'required' );
9570 .removeAttr( 'required' )
9571 .removeAttr( 'aria-required' );
9572 if ( this.getIndicator() === 'required' ) {
9573 this.setIndicator( null );
9576 this.updateSearchIndicator();
9581 * Support function for making #onElementAttach work across browsers.
9583 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9584 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9586 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9587 * first time that the element gets attached to the documented.
9589 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9590 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9591 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9594 if ( MutationObserver
) {
9595 // The new way. If only it wasn't so ugly.
9597 if ( this.isElementAttached() ) {
9598 // Widget is attached already, do nothing. This breaks the functionality of this function when
9599 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9600 // would require observation of the whole document, which would hurt performance of other,
9601 // more important code.
9605 // Find topmost node in the tree
9606 topmostNode
= this.$element
[ 0 ];
9607 while ( topmostNode
.parentNode
) {
9608 topmostNode
= topmostNode
.parentNode
;
9611 // We have no way to detect the $element being attached somewhere without observing the entire
9612 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9613 // parent node of $element, and instead detect when $element is removed from it (and thus
9614 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9615 // doesn't get attached, we end up back here and create the parent.
9617 mutationObserver
= new MutationObserver( function ( mutations
) {
9618 var i
, j
, removedNodes
;
9619 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9620 removedNodes
= mutations
[ i
].removedNodes
;
9621 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9622 if ( removedNodes
[ j
] === topmostNode
) {
9623 setTimeout( onRemove
, 0 );
9630 onRemove = function () {
9631 // If the node was attached somewhere else, report it
9632 if ( widget
.isElementAttached() ) {
9633 widget
.onElementAttach();
9635 mutationObserver
.disconnect();
9636 widget
.installParentChangeDetector();
9639 // Create a fake parent and observe it
9640 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9641 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9643 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9644 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9645 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9650 * Automatically adjust the size of the text input.
9652 * This only affects #multiline inputs that are {@link #autosize autosized}.
9657 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9658 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9659 idealHeight
, newHeight
, scrollWidth
, property
;
9661 if ( this.isWaitingToBeAttached
) {
9662 // #onElementAttach will be called soon, which calls this method
9666 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9667 if ( this.autosize
) {
9669 .val( this.$input
.val() )
9670 .attr( 'rows', this.minRows
)
9671 // Set inline height property to 0 to measure scroll height
9672 .css( 'height', 0 );
9674 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9676 this.valCache
= this.$input
.val();
9678 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9680 // Remove inline height property to measure natural heights
9681 this.$clone
.css( 'height', '' );
9682 innerHeight
= this.$clone
.innerHeight();
9683 outerHeight
= this.$clone
.outerHeight();
9685 // Measure max rows height
9687 .attr( 'rows', this.maxRows
)
9688 .css( 'height', 'auto' )
9690 maxInnerHeight
= this.$clone
.innerHeight();
9692 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9693 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9694 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9695 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9697 this.$clone
.addClass( 'oo-ui-element-hidden' );
9699 // Only apply inline height when expansion beyond natural height is needed
9700 // Use the difference between the inner and outer height as a buffer
9701 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9702 if ( newHeight
!== this.styleHeight
) {
9703 this.$input
.css( 'height', newHeight
);
9704 this.styleHeight
= newHeight
;
9705 this.emit( 'resize' );
9708 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9709 if ( scrollWidth
!== this.scrollWidth
) {
9710 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9712 this.$label
.css( { right
: '', left
: '' } );
9713 this.$indicator
.css( { right
: '', left
: '' } );
9715 if ( scrollWidth
) {
9716 this.$indicator
.css( property
, scrollWidth
);
9717 if ( this.labelPosition
=== 'after' ) {
9718 this.$label
.css( property
, scrollWidth
);
9722 this.scrollWidth
= scrollWidth
;
9723 this.positionLabel();
9733 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9734 if ( config
.multiline
) {
9735 return $( '<textarea>' );
9736 } else if ( this.getSaneType( config
) === 'number' ) {
9737 return $( '<input>' )
9738 .attr( 'step', 'any' )
9739 .attr( 'type', 'number' );
9741 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9746 * Get sanitized value for 'type' for given config.
9748 * @param {Object} config Configuration options
9749 * @return {string|null}
9752 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9753 var allowedTypes
= [
9761 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9765 * Check if the input supports multiple lines.
9769 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9770 return !!this.multiline
;
9774 * Check if the input automatically adjusts its size.
9778 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9779 return !!this.autosize
;
9783 * Focus the input and select a specified range within the text.
9785 * @param {number} from Select from offset
9786 * @param {number} [to] Select to offset, defaults to from
9789 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9790 var isBackwards
, start
, end
,
9791 input
= this.$input
[ 0 ];
9795 isBackwards
= to
< from;
9796 start
= isBackwards
? to
: from;
9797 end
= isBackwards
? from : to
;
9802 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9804 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9805 // Rather than expensively check if the input is attached every time, just check
9806 // if it was the cause of an error being thrown. If not, rethrow the error.
9807 if ( this.getElementDocument().body
.contains( input
) ) {
9815 * Get an object describing the current selection range in a directional manner
9817 * @return {Object} Object containing 'from' and 'to' offsets
9819 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9820 var input
= this.$input
[ 0 ],
9821 start
= input
.selectionStart
,
9822 end
= input
.selectionEnd
,
9823 isBackwards
= input
.selectionDirection
=== 'backward';
9826 from: isBackwards
? end
: start
,
9827 to
: isBackwards
? start
: end
9832 * Get the length of the text input value.
9834 * This could differ from the length of #getValue if the
9835 * value gets filtered
9837 * @return {number} Input length
9839 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9840 return this.$input
[ 0 ].value
.length
;
9844 * Focus the input and select the entire text.
9848 OO
.ui
.TextInputWidget
.prototype.select = function () {
9849 return this.selectRange( 0, this.getInputLength() );
9853 * Focus the input and move the cursor to the start.
9857 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9858 return this.selectRange( 0 );
9862 * Focus the input and move the cursor to the end.
9866 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9867 return this.selectRange( this.getInputLength() );
9871 * Insert new content into the input.
9873 * @param {string} content Content to be inserted
9876 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9878 range
= this.getRange(),
9879 value
= this.getValue();
9881 start
= Math
.min( range
.from, range
.to
);
9882 end
= Math
.max( range
.from, range
.to
);
9884 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9885 this.selectRange( start
+ content
.length
);
9890 * Insert new content either side of a selection.
9892 * @param {string} pre Content to be inserted before the selection
9893 * @param {string} post Content to be inserted after the selection
9896 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9898 range
= this.getRange(),
9899 offset
= pre
.length
;
9901 start
= Math
.min( range
.from, range
.to
);
9902 end
= Math
.max( range
.from, range
.to
);
9904 this.selectRange( start
).insertContent( pre
);
9905 this.selectRange( offset
+ end
).insertContent( post
);
9907 this.selectRange( offset
+ start
, offset
+ end
);
9912 * Set the validation pattern.
9914 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9915 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9916 * value must contain only numbers).
9918 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9919 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9921 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9922 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9923 this.validate
= validate
;
9925 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9930 * Sets the 'invalid' flag appropriately.
9932 * @param {boolean} [isValid] Optionally override validation result
9934 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9936 setFlag = function ( valid
) {
9938 widget
.$input
.attr( 'aria-invalid', 'true' );
9940 widget
.$input
.removeAttr( 'aria-invalid' );
9942 widget
.setFlags( { invalid
: !valid
} );
9945 if ( isValid
!== undefined ) {
9948 this.getValidity().then( function () {
9957 * Get the validity of current value.
9959 * This method returns a promise that resolves if the value is valid and rejects if
9960 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9962 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9964 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
9967 function rejectOrResolve( valid
) {
9969 return $.Deferred().resolve().promise();
9971 return $.Deferred().reject().promise();
9975 // Check browser validity and reject if it is invalid
9977 this.$input
[ 0 ].checkValidity
!== undefined &&
9978 this.$input
[ 0 ].checkValidity() === false
9980 return rejectOrResolve( false );
9983 // Run our checks if the browser thinks the field is valid
9984 if ( this.validate
instanceof Function
) {
9985 result
= this.validate( this.getValue() );
9986 if ( result
&& $.isFunction( result
.promise
) ) {
9987 return result
.promise().then( function ( valid
) {
9988 return rejectOrResolve( valid
);
9991 return rejectOrResolve( result
);
9994 return rejectOrResolve( this.getValue().match( this.validate
) );
9999 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10001 * @param {string} labelPosition Label position, 'before' or 'after'
10004 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10005 this.labelPosition
= labelPosition
;
10006 if ( this.label
) {
10007 // If there is no label and we only change the position, #updatePosition is a no-op,
10008 // but it takes really a lot of work to do nothing.
10009 this.updatePosition();
10015 * Update the position of the inline label.
10017 * This method is called by #setLabelPosition, and can also be called on its own if
10018 * something causes the label to be mispositioned.
10022 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10023 var after
= this.labelPosition
=== 'after';
10026 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10027 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10029 this.valCache
= null;
10030 this.scrollWidth
= null;
10032 this.positionLabel();
10038 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
10039 * already empty or when it's not editable.
10041 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
10042 if ( this.type
=== 'search' ) {
10043 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10044 this.setIndicator( null );
10046 this.setIndicator( 'clear' );
10052 * Position the label by setting the correct padding on the input.
10057 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10058 var after
, rtl
, property
;
10060 if ( this.isWaitingToBeAttached
) {
10061 // #onElementAttach will be called soon, which calls this method
10065 // Clear old values
10067 // Clear old values if present
10069 'padding-right': '',
10073 if ( this.label
) {
10074 this.$element
.append( this.$label
);
10076 this.$label
.detach();
10080 after
= this.labelPosition
=== 'after';
10081 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10082 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10084 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10092 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10093 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10094 if ( state
.scrollTop
!== undefined ) {
10095 this.$input
.scrollTop( state
.scrollTop
);
10101 * @extends OO.ui.TextInputWidget
10104 * @param {Object} [config] Configuration options
10106 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10107 config
= $.extend( {
10111 // Set type to text so that TextInputWidget doesn't
10112 // get stuck in an infinite loop.
10113 config
.type
= 'text';
10115 // Parent constructor
10116 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10119 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10120 this.updateSearchIndicator();
10121 this.connect( this, {
10122 disable
: 'onDisable'
10128 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10136 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10137 return $( '<input>' ).attr( 'type', 'search' );
10143 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10144 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10145 // Clear the text field
10146 this.setValue( '' );
10147 this.$input
[ 0 ].focus();
10153 * Update the 'clear' indicator displayed on type: 'search' text
10154 * fields, hiding it when the field is already empty or when it's not
10157 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10158 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10159 this.setIndicator( null );
10161 this.setIndicator( 'clear' );
10168 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10169 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10170 this.updateSearchIndicator();
10174 * Handle disable events.
10176 * @param {boolean} disabled Element is disabled
10179 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10180 this.updateSearchIndicator();
10186 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10187 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10188 this.updateSearchIndicator();
10193 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10194 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10195 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10197 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10198 * option, that option will appear to be selected.
10199 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10202 * After the user chooses an option, its `data` will be used as a new value for the widget.
10203 * A `label` also can be specified for each option: if given, it will be shown instead of the
10204 * `data` in the dropdown menu.
10206 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10208 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10211 * // Example: A ComboBoxInputWidget.
10212 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10213 * value: 'Option 1',
10215 * { data: 'Option 1' },
10216 * { data: 'Option 2' },
10217 * { data: 'Option 3' }
10220 * $( 'body' ).append( comboBox.$element );
10223 * // Example: A ComboBoxInputWidget with additional option labels.
10224 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10225 * value: 'Option 1',
10228 * data: 'Option 1',
10229 * label: 'Option One'
10232 * data: 'Option 2',
10233 * label: 'Option Two'
10236 * data: 'Option 3',
10237 * label: 'Option Three'
10241 * $( 'body' ).append( comboBox.$element );
10243 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10246 * @extends OO.ui.TextInputWidget
10249 * @param {Object} [config] Configuration options
10250 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10251 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
10252 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10253 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10254 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10256 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10257 // Configuration initialization
10258 config
= $.extend( {
10259 autocomplete
: false
10262 // ComboBoxInputWidget shouldn't support multiline
10263 config
.multiline
= false;
10265 // Parent constructor
10266 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10269 this.$overlay
= config
.$overlay
|| this.$element
;
10270 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10271 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10273 disabled
: this.disabled
10275 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
10279 $container
: this.$element
,
10280 disabled
: this.isDisabled()
10286 this.connect( this, {
10287 change
: 'onInputChange',
10288 enter
: 'onInputEnter'
10290 this.dropdownButton
.connect( this, {
10291 click
: 'onDropdownButtonClick'
10293 this.menu
.connect( this, {
10294 choose
: 'onMenuChoose',
10295 add
: 'onMenuItemsChange',
10296 remove
: 'onMenuItemsChange'
10300 this.$input
.attr( {
10302 'aria-autocomplete': 'list'
10304 // Do not override options set via config.menu.items
10305 if ( config
.options
!== undefined ) {
10306 this.setOptions( config
.options
);
10308 this.$field
= $( '<div>' )
10309 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10310 .append( this.$input
, this.dropdownButton
.$element
);
10312 .addClass( 'oo-ui-comboBoxInputWidget' )
10313 .append( this.$field
);
10314 this.$overlay
.append( this.menu
.$element
);
10315 this.onMenuItemsChange();
10320 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10325 * Get the combobox's menu.
10327 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
10329 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10334 * Get the combobox's text input widget.
10336 * @return {OO.ui.TextInputWidget} Text input widget
10338 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10343 * Handle input change events.
10346 * @param {string} value New value
10348 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10349 var match
= this.menu
.getItemFromData( value
);
10351 this.menu
.selectItem( match
);
10352 if ( this.menu
.getHighlightedItem() ) {
10353 this.menu
.highlightItem( match
);
10356 if ( !this.isDisabled() ) {
10357 this.menu
.toggle( true );
10362 * Handle input enter events.
10366 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10367 if ( !this.isDisabled() ) {
10368 this.menu
.toggle( false );
10373 * Handle button click events.
10377 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10378 this.menu
.toggle();
10379 this.$input
[ 0 ].focus();
10383 * Handle menu choose events.
10386 * @param {OO.ui.OptionWidget} item Chosen item
10388 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10389 this.setValue( item
.getData() );
10393 * Handle menu item change events.
10397 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10398 var match
= this.menu
.getItemFromData( this.getValue() );
10399 this.menu
.selectItem( match
);
10400 if ( this.menu
.getHighlightedItem() ) {
10401 this.menu
.highlightItem( match
);
10403 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10409 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10411 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10413 if ( this.dropdownButton
) {
10414 this.dropdownButton
.setDisabled( this.isDisabled() );
10417 this.menu
.setDisabled( this.isDisabled() );
10424 * Set the options available for this input.
10426 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10429 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10432 .addItems( options
.map( function ( opt
) {
10433 return new OO
.ui
.MenuOptionWidget( {
10435 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10443 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10444 * which is a widget that is specified by reference before any optional configuration settings.
10446 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10448 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10449 * A left-alignment is used for forms with many fields.
10450 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10451 * A right-alignment is used for long but familiar forms which users tab through,
10452 * verifying the current field with a quick glance at the label.
10453 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10454 * that users fill out from top to bottom.
10455 * - **inline**: The label is placed after the field-widget and aligned to the left.
10456 * An inline-alignment is best used with checkboxes or radio buttons.
10458 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10459 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10461 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10464 * @extends OO.ui.Layout
10465 * @mixins OO.ui.mixin.LabelElement
10466 * @mixins OO.ui.mixin.TitledElement
10469 * @param {OO.ui.Widget} fieldWidget Field widget
10470 * @param {Object} [config] Configuration options
10471 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10472 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10473 * The array may contain strings or OO.ui.HtmlSnippet instances.
10474 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10475 * The array may contain strings or OO.ui.HtmlSnippet instances.
10476 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10477 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10478 * For important messages, you are advised to use `notices`, as they are always shown.
10479 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10481 * @throws {Error} An error is thrown if no widget is specified
10483 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10484 // Allow passing positional parameters inside the config object
10485 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10486 config
= fieldWidget
;
10487 fieldWidget
= config
.fieldWidget
;
10490 // Make sure we have required constructor arguments
10491 if ( fieldWidget
=== undefined ) {
10492 throw new Error( 'Widget not found' );
10495 // Configuration initialization
10496 config
= $.extend( { align
: 'left' }, config
);
10498 // Parent constructor
10499 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10501 // Mixin constructors
10502 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10503 $label
: $( '<label>' )
10505 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10508 this.fieldWidget
= fieldWidget
;
10511 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10512 this.$messages
= $( '<ul>' );
10513 this.$header
= $( '<span>' );
10514 this.$body
= $( '<div>' );
10516 if ( config
.help
) {
10517 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10518 $overlay
: config
.$overlay
,
10522 classes
: [ 'oo-ui-fieldLayout-help' ],
10526 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10527 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10529 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10531 this.$help
= this.popupButtonWidget
.$element
;
10533 this.$help
= $( [] );
10537 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10540 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10541 if ( this.fieldWidget
.getInputId() ) {
10542 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10544 this.$label
.on( 'click', function () {
10545 this.fieldWidget
.focus();
10551 .addClass( 'oo-ui-fieldLayout' )
10552 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10553 .append( this.$body
);
10554 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10555 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10556 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10558 .addClass( 'oo-ui-fieldLayout-field' )
10559 .append( this.fieldWidget
.$element
);
10561 this.setErrors( config
.errors
|| [] );
10562 this.setNotices( config
.notices
|| [] );
10563 this.setAlignment( config
.align
);
10568 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10569 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10570 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10575 * Handle field disable events.
10578 * @param {boolean} value Field is disabled
10580 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10581 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10585 * Get the widget contained by the field.
10587 * @return {OO.ui.Widget} Field widget
10589 OO
.ui
.FieldLayout
.prototype.getField = function () {
10590 return this.fieldWidget
;
10594 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10595 * #setAlignment). Return `false` if it can't or if this can't be determined.
10597 * @return {boolean}
10599 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10600 // This is very simplistic, but should be good enough.
10601 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10606 * @param {string} kind 'error' or 'notice'
10607 * @param {string|OO.ui.HtmlSnippet} text
10610 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10611 var $listItem
, $icon
, message
;
10612 $listItem
= $( '<li>' );
10613 if ( kind
=== 'error' ) {
10614 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10615 } else if ( kind
=== 'notice' ) {
10616 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10620 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10622 .append( $icon
, message
.$element
)
10623 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10628 * Set the field alignment mode.
10631 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10634 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10635 if ( value
!== this.align
) {
10636 // Default to 'left'
10637 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10641 if ( value
=== 'inline' && !this.isFieldInline() ) {
10644 // Reorder elements
10645 if ( value
=== 'top' ) {
10646 this.$header
.append( this.$label
, this.$help
);
10647 this.$body
.append( this.$header
, this.$field
);
10648 } else if ( value
=== 'inline' ) {
10649 this.$header
.append( this.$label
, this.$help
);
10650 this.$body
.append( this.$field
, this.$header
);
10652 this.$header
.append( this.$label
);
10653 this.$body
.append( this.$header
, this.$help
, this.$field
);
10655 // Set classes. The following classes can be used here:
10656 // * oo-ui-fieldLayout-align-left
10657 // * oo-ui-fieldLayout-align-right
10658 // * oo-ui-fieldLayout-align-top
10659 // * oo-ui-fieldLayout-align-inline
10660 if ( this.align
) {
10661 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10663 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10664 this.align
= value
;
10671 * Set the list of error messages.
10673 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10674 * The array may contain strings or OO.ui.HtmlSnippet instances.
10677 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10678 this.errors
= errors
.slice();
10679 this.updateMessages();
10684 * Set the list of notice messages.
10686 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10687 * The array may contain strings or OO.ui.HtmlSnippet instances.
10690 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10691 this.notices
= notices
.slice();
10692 this.updateMessages();
10697 * Update the rendering of error and notice messages.
10701 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10703 this.$messages
.empty();
10705 if ( this.errors
.length
|| this.notices
.length
) {
10706 this.$body
.after( this.$messages
);
10708 this.$messages
.remove();
10712 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10713 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10715 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10716 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10721 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10722 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10723 * is required and is specified before any optional configuration settings.
10725 * Labels can be aligned in one of four ways:
10727 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10728 * A left-alignment is used for forms with many fields.
10729 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10730 * A right-alignment is used for long but familiar forms which users tab through,
10731 * verifying the current field with a quick glance at the label.
10732 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10733 * that users fill out from top to bottom.
10734 * - **inline**: The label is placed after the field-widget and aligned to the left.
10735 * An inline-alignment is best used with checkboxes or radio buttons.
10737 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10738 * text is specified.
10741 * // Example of an ActionFieldLayout
10742 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10743 * new OO.ui.TextInputWidget( {
10744 * placeholder: 'Field widget'
10746 * new OO.ui.ButtonWidget( {
10750 * label: 'An ActionFieldLayout. This label is aligned top',
10752 * help: 'This is help text'
10756 * $( 'body' ).append( actionFieldLayout.$element );
10759 * @extends OO.ui.FieldLayout
10762 * @param {OO.ui.Widget} fieldWidget Field widget
10763 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10764 * @param {Object} config
10766 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10767 // Allow passing positional parameters inside the config object
10768 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10769 config
= fieldWidget
;
10770 fieldWidget
= config
.fieldWidget
;
10771 buttonWidget
= config
.buttonWidget
;
10774 // Parent constructor
10775 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10778 this.buttonWidget
= buttonWidget
;
10779 this.$button
= $( '<span>' );
10780 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10784 .addClass( 'oo-ui-actionFieldLayout' );
10786 .addClass( 'oo-ui-actionFieldLayout-button' )
10787 .append( this.buttonWidget
.$element
);
10789 .addClass( 'oo-ui-actionFieldLayout-input' )
10790 .append( this.fieldWidget
.$element
);
10792 .append( this.$input
, this.$button
);
10797 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10800 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10801 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10802 * configured with a label as well. For more information and examples,
10803 * please see the [OOjs UI documentation on MediaWiki][1].
10806 * // Example of a fieldset layout
10807 * var input1 = new OO.ui.TextInputWidget( {
10808 * placeholder: 'A text input field'
10811 * var input2 = new OO.ui.TextInputWidget( {
10812 * placeholder: 'A text input field'
10815 * var fieldset = new OO.ui.FieldsetLayout( {
10816 * label: 'Example of a fieldset layout'
10819 * fieldset.addItems( [
10820 * new OO.ui.FieldLayout( input1, {
10821 * label: 'Field One'
10823 * new OO.ui.FieldLayout( input2, {
10824 * label: 'Field Two'
10827 * $( 'body' ).append( fieldset.$element );
10829 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10832 * @extends OO.ui.Layout
10833 * @mixins OO.ui.mixin.IconElement
10834 * @mixins OO.ui.mixin.LabelElement
10835 * @mixins OO.ui.mixin.GroupElement
10838 * @param {Object} [config] Configuration options
10839 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10840 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10841 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10842 * For important messages, you are advised to use `notices`, as they are always shown.
10843 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10845 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10846 // Configuration initialization
10847 config
= config
|| {};
10849 // Parent constructor
10850 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10852 // Mixin constructors
10853 OO
.ui
.mixin
.IconElement
.call( this, config
);
10854 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10855 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10858 this.$header
= $( '<div>' );
10859 if ( config
.help
) {
10860 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10861 $overlay
: config
.$overlay
,
10865 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10869 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10870 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10872 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10874 this.$help
= this.popupButtonWidget
.$element
;
10876 this.$help
= $( [] );
10881 .addClass( 'oo-ui-fieldsetLayout-header' )
10882 .append( this.$icon
, this.$label
, this.$help
);
10883 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10885 .addClass( 'oo-ui-fieldsetLayout' )
10886 .prepend( this.$header
, this.$group
);
10887 if ( Array
.isArray( config
.items
) ) {
10888 this.addItems( config
.items
);
10894 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10895 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10896 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10897 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10899 /* Static Properties */
10905 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10908 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10909 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10910 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10911 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10913 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10914 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10915 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10916 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10917 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10918 * often have simplified APIs to match the capabilities of HTML forms.
10919 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10921 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10922 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10925 * // Example of a form layout that wraps a fieldset layout
10926 * var input1 = new OO.ui.TextInputWidget( {
10927 * placeholder: 'Username'
10929 * var input2 = new OO.ui.TextInputWidget( {
10930 * placeholder: 'Password',
10933 * var submit = new OO.ui.ButtonInputWidget( {
10937 * var fieldset = new OO.ui.FieldsetLayout( {
10938 * label: 'A form layout'
10940 * fieldset.addItems( [
10941 * new OO.ui.FieldLayout( input1, {
10942 * label: 'Username',
10945 * new OO.ui.FieldLayout( input2, {
10946 * label: 'Password',
10949 * new OO.ui.FieldLayout( submit )
10951 * var form = new OO.ui.FormLayout( {
10952 * items: [ fieldset ],
10953 * action: '/api/formhandler',
10956 * $( 'body' ).append( form.$element );
10959 * @extends OO.ui.Layout
10960 * @mixins OO.ui.mixin.GroupElement
10963 * @param {Object} [config] Configuration options
10964 * @cfg {string} [method] HTML form `method` attribute
10965 * @cfg {string} [action] HTML form `action` attribute
10966 * @cfg {string} [enctype] HTML form `enctype` attribute
10967 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10969 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
10972 // Configuration initialization
10973 config
= config
|| {};
10975 // Parent constructor
10976 OO
.ui
.FormLayout
.parent
.call( this, config
);
10978 // Mixin constructors
10979 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10982 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
10984 // Make sure the action is safe
10985 action
= config
.action
;
10986 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
10987 action
= './' + action
;
10992 .addClass( 'oo-ui-formLayout' )
10994 method
: config
.method
,
10996 enctype
: config
.enctype
10998 if ( Array
.isArray( config
.items
) ) {
10999 this.addItems( config
.items
);
11005 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11006 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11011 * A 'submit' event is emitted when the form is submitted.
11016 /* Static Properties */
11022 OO
.ui
.FormLayout
.static.tagName
= 'form';
11027 * Handle form submit events.
11030 * @param {jQuery.Event} e Submit event
11033 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11034 if ( this.emit( 'submit' ) ) {
11040 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11041 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11044 * // Example of a panel layout
11045 * var panel = new OO.ui.PanelLayout( {
11049 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11051 * $( 'body' ).append( panel.$element );
11054 * @extends OO.ui.Layout
11057 * @param {Object} [config] Configuration options
11058 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11059 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11060 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11061 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11063 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11064 // Configuration initialization
11065 config
= $.extend( {
11072 // Parent constructor
11073 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11076 this.$element
.addClass( 'oo-ui-panelLayout' );
11077 if ( config
.scrollable
) {
11078 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11080 if ( config
.padded
) {
11081 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11083 if ( config
.expanded
) {
11084 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11086 if ( config
.framed
) {
11087 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11093 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11098 * Focus the panel layout
11100 * The default implementation just focuses the first focusable element in the panel
11102 OO
.ui
.PanelLayout
.prototype.focus = function () {
11103 OO
.ui
.findFocusable( this.$element
).focus();
11107 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11108 * items), with small margins between them. Convenient when you need to put a number of block-level
11109 * widgets on a single line next to each other.
11111 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11114 * // HorizontalLayout with a text input and a label
11115 * var layout = new OO.ui.HorizontalLayout( {
11117 * new OO.ui.LabelWidget( { label: 'Label' } ),
11118 * new OO.ui.TextInputWidget( { value: 'Text' } )
11121 * $( 'body' ).append( layout.$element );
11124 * @extends OO.ui.Layout
11125 * @mixins OO.ui.mixin.GroupElement
11128 * @param {Object} [config] Configuration options
11129 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11131 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11132 // Configuration initialization
11133 config
= config
|| {};
11135 // Parent constructor
11136 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11138 // Mixin constructors
11139 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11142 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11143 if ( Array
.isArray( config
.items
) ) {
11144 this.addItems( config
.items
);
11150 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11151 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);